给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
int strStr(string haystack, string needle) {
if(needle == "") return 0;
int len1 = haystack.length();
int len2 = needle.length();
if(len2 > len1) return -1;
int i = 0, j = 0;
while(i < len1 && j < len2){
if(haystack[i] == needle[j]){
i++;
j++;
}
else{
i = i-j+1;
j = 0;
}
printf("%d %d\n", i, j);
}
if(j == len2) return i - j;
else return -1;
}