使用kmp解决。
kmp流程:构建前缀表-搜索。
前缀表(记录字符串中每个字串最大相等前后缀的长度)构建:
以aabaaf为例:
1、‘a'没有前后缀,所以next[0] = 0;
2、’aa‘,前后缀都为a,所以next[1]=1;
3、’aab‘,前缀啊,后缀b,没有前后缀,所以next[2]=0;
4、’aaba‘,最大相等前后缀为a,所以next[3]=1;
5、’aabaa‘,最大相等前后缀为aa,所以next[4]=2;
6、’aabaaf‘,最大相等前后缀为0,所以next[5]=0
对应前缀表代码
public void getNext(String str, int[] next) { int j = 0; next[0] = 0; //i对应的为模式串中的后缀,从1开始,j表示前缀,从0开始 //当ij对应相等则j++,否则j-- for (int i = 1; i < str.length(); i++) { while (j > 0 && str.charAt(i) != str.charAt(j)) j = next[j - 1]; if (str.charAt(i) == str.charAt(j)) j++; next[i] = j; } }
对应搜索代码
public int strStr(String haystack, String needle) { if (haystack.length() == 0) return 0; int[] next = new int[needle.length()]; getNext(needle, next); int j = 0; for (int i = 0; i < haystack.length(); i++) { //回退模式串 while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = next[j - 1]; if (haystack.charAt(i) == needle.charAt(j)) j++; if (j == needle.length()) return i - needle.length() + 1; } return -1; }