Leetcode 28. 实现 strStr()
思路
暴力解法:遍历字符串,让其与needle逐个元素对比,若相同则指针都加1,若不同则回退到主字符串的下一个元素与needle从头开始比较。
代码
int strStr(string haystack, string needle) {
int j = 0;
int i = 0;
int res = 0;
while(i<haystack.length()&& j<needle.length()){
if (haystack[i] == needle[j]) { //如果两数相等则往后一位
i++;
j++;
}
else { //不相等则主字符串往后j位的下一位,与needle从头开始比较
i = i - j + 1;
j = 0;
}
}
//cout << i << j << endl;
if (j == needle.length()) { //如果与needle都比较完了证明存在子字符串
res = i - j;
}
else res = -1;//否则不存在
return res;
}
总结
kmp算法暂时还没看懂,以后有机会要学习一下。