可以调用库函数 source.indexOf(target);
BF (Brute-Force) 暴力搜索算法,最好情况时间复杂度为O(m), 最差和平均时间复杂度为O(n * m)
KMP算法 时间复杂度O(n)
(为什么叫KMP,这个算法由三个人共同提出,KMP是3个人名字首字母的组合)
BF算法代码如下,双指针,匹配失败则回溯,主串回溯到原来的起始位置,
j-i(我前面有几个元素,我的索引就是几)
再往后一格 j-i+1
public class Solution {
/**
* @param source:
* @param target:
* @return: return the index
*/
public int strStr(String source, String target) {
// Write your code here
//直接调用库函数 return source.indexOf(target); 较慢
//bf算法,nm的时间复杂度
int i=0;
int j=0;
while(j<target.length()&&i<source.length()){
if(source.charAt(i)==target.charAt(j)){
i++;
j++;
}else{
i=i-j+1;//i-j是“走过的source串”比“走过的
//模式串”多出来的长度
//其值等于source串这趟匹配的起始位置。
//索引从0开始,我前面有几个元素,我的索引就是几
//加1是匹配失败了,回溯后需要往后走一步
j=0;
}
}
if(j==target.length()){
//退出匹配的原因是找到了
return i-target.length();
}else{
return -1;
}
}
}