String search-strStr

Source: Internet
Author: User

String search-strStr
String search-strStrProblem description

String search (also called string SEARCH) is a useful function in string operations. Your task is to implement this function.

For a given source string and a target string, you should find the first position (starting from 0) of the target string in the source string ).

If not,-1 is returned.

Have you ever encountered this question during a real interview? Yes
Example
If source = "source" and target = "target",-1 is returned.

If source = "abcdabcdefg" and target = "bcd", 1 is returned.

Challenges
O (n2) algorithms are acceptable. It would be better if you could use the O (n) algorithm. (Tip: KMP)

Description
Do I need to implement the KMP algorithm during the interview?

No. When this problem occurs during an interview, the interviewer may just want to test your basic application capabilities. Of course, you must first confirm with the interviewer how to implement this question.
Label Expand

Reference Code
class Solution {public:    /**     * Returns a index to the first occurrence of target in source,     * or -1  if target is not part of source.     * @param source string to be scanned.     * @param target string containing the sequence of characters to match.     */    int strStr(const char *source, const char *target) {        // write your code here        int i = 0, j = 0;        if (source == NULL || target == NULL)            return -1;        while (source[i] != ''&&target[j] != '') {            if (source[i] == target[j]) {                i++;                j++;            } else {                i = i - j + 1;                j = 0;            }        }        if (target[j] == '')            return i - j;        return -1;    }};

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.