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; }};