主要是注意badcase.
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle == "" && haystack == "") return 0;
if (needle == "") return 0;
if(haystack == needle ) return 0;
int len_hay = haystack.length();
int len_needle = needle.length();
for(int i = 0; i<= len_hay - len_needle; i++){ // 这里是<= ,不是小于。
if(haystack.substr(i, len_needle) == needle) return i;
}
return -1;
}
};
本文深入探讨了字符串匹配算法中的KMP算法和朴素匹配算法。通过详细的代码解析,讲解了如何在C++中实现这些算法,并特别关注了边界情况处理,如空字符串的匹配。文章还提供了完整的代码示例,帮助读者理解并掌握字符串匹配的技巧。
536

被折叠的 条评论
为什么被折叠?



