思路:
方法一:
时间复杂度O(N+k*M)
class Solution {
public:
int strStr(string haystack, string needle) {
int hsize = static_cast<int>(haystack.size());
int nsize = static_cast<int>(needle.size());
if(hsize < nsize) return -1;
if(nsize == 0) return 0;
int i,j;
for (i = j = 0; haystack[i] && needle[j];) {
if (haystack[i] == needle[j]) {
++i;
++j;
if(j == nsize) return i-j;
} else {
i = i - j + 1;
j = 0;
}
}
return -1;
}
};
java code:
public class Solution {
public int strStr(String source, String target) {
if(source == null || target == null) return -1;
if(source.length() < target.length()) return -1;
if(target.length() == 0) return 0;
for(int i = 0, j = 0; i < source.length() && j < target.length(); ) {
if(source.charAt(i) == target.charAt(j)) {
++i;
++j;
if(j == target.length()) return i - j;
}else {
i = i - j + 1;
j = 0;
}
}
return -1;
}
}
方法二:KMP
本文介绍了一种简单的字符串匹配算法实现,通过逐字符比较的方式寻找目标子串在源串中的位置。该方法适用于基本的字符串搜索场景,并为理解更复杂的KMP算法等提供了基础。
910

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



