@[TOC](LeetCode 第28题 实现strStr() 做题记录)
题目描述
我的解法
思路
最直接的方法——暴力求解
两层循环,时间复杂度O(mn) m和n分别是两个字符串的长度
上面超出时间限制了,那就不得不用KMP算法了
对应Java代码
执行时超出了时间限制
class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0) {
return 0;
}
int hj,ni;
for(int hi = 0; hi < haystack.length(); hi ++){
hj = hi;
ni = 0;
while(haystack.charAt(hj) == needle.charAt(ni)){
if(ni == needle.length() - 1){
return hi;
}
if(hj == haystack.length() - 1){
break;
}
hj++;
ni++;
}
}
return -1;
}
}
更优解法
此部分转载于公众号代码随想录
思路
KMP算法
对应Java代码
class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0){ return 0; }
int nLen = needle.length();
int hLen = haystack.length();
int[] next = new int[nLen];
getNext(next, needle);
int j = -1;
for(int i = 0; i < hLen; i++){
while( j >= 0 && haystack.charAt(i) != needle.charAt(j + 1)){
j = next[j];
}
if(haystack.charAt(i) == needle.charAt(j + 1)){
j++;
}
if(j == nLen - 1){
return i - nLen + 1;
}
}
return -1;
}
public void getNext(int[] next, String needle){
int j = -1; //定义前缀
next[0] = j;
for(int i = 1; i < next.length; i++){
while(j >= 0 && needle.charAt(i) != needle.charAt(j + 1)){
j = next[j];
}
if(needle.charAt(i) == needle.charAt(j + 1)){
j++;
}
next[i] = j;
}
}
}
复杂度分析
时间复杂度:O(m + n) m和n分别是文本串和模式串的长度
空间复杂度:O(n) 用来存储模式串的next数组
收获总结
KMP算法的原理和实践写法