KMP真的难,先做个记录吧
28. 找出字符串中第一个匹配项的下标
class Solution {
private int[][] dp;
private String pat;
// 构建 DP 表
private void buildDp(String pat) {
int M = pat.length();
dp = new int[M][256];
dp[0][pat.charAt(0)] = 1;
int X = 0;
for (int j = 1; j < M; j++) {
for (int c = 0; c < 256; c++) {
dp[j][c] = dp[X][c];
}
dp[j][pat.charAt(j)] = j + 1;
X = dp[X][pat.charAt(j)];
}
}
// KMP 搜索函数
public int search(String txt) {
int M = pat.length();
int N = txt.length();
int j = 0;
for (int i = 0; i < N; i++) {
j = dp[j][txt.charAt(i)];
if (j == M) return i - M + 1;
}
return -1;
}
// 用 KMP 实现的 strStr 函数
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0;
}
if (haystack == null || haystack.length() == 0) {
return -1;
}
this.pat = needle;
buildDp(needle);
return search(haystack);
}
}
459. 重复的子字符串
判断字符串s是否由重复子串组成,只要两个s拼接在一起,里面还出现一个s的话,就说明是由重复子串组成。
class Solution {
public boolean repeatedSubstringPattern(String s) {
String tmp = s + s;
tmp = tmp.substring(1, tmp.length() - 1);
if(tmp.indexOf(s) > -1){
return true;
}
return false;
}
}