Problem:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题说简单,说难可能也会有一点点难度,如果case特别挑剔的话,可能会超时,需要用到KMP算法。我先写了一个比较简单的算法,发现AC了。如果用传统的一位一位比较,一直比较到haystack的最后一位的话,会超时的。这里要注意haystack和needle的长度,假定needle的长度比较长的话,比较到haystack最后一位会浪费很多时间,所以当needle的长度大于haystack未遍历的时候,是可以返回-1的了。代码中的s2Length - s1Length + 1就是表示这个情况。
Code:
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack == "" && needle != "") {
return -1;
}
int s1Length = haystack.length();
int s2Length = needle.length();
for (int i = 0; i < s1Length - s2Length + 1; i++) {
int j = 0;
for (; j < s2Length; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == s2Length) {
return i;
}
}
return -1;
}
};