1. 字符串匹配(KMP)
KMP 算法详解 - 知乎 (zhihu.com)
class Solution {
public boolean repeatedSubstringPattern(String s) {
if(s.equals("")) return false;
int m = s.length();
String txt = s + s;
txt = txt.substring(1, 2*m-1);
int n = 2*m - 2;
int[][] dp = new int[m][256];
dp[0][s.charAt(0)] = 1;
int X = 0;
for(int j=1;j<m;j++){
for(int c='a';c<'z';c++) dp[j][c] = dp[X][c];
dp[j][s.charAt(j)] = j+1;
X = dp[X][s.charAt(j)];
}
int j = 0;
for(int i=0;i<n;i++){
j = dp[j][txt.charAt(i)];
if(j == m) return true;
}
return false;
}
}
2. 回文子串
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int ans = n;
for(int i=0;i<n;i++){
int left = i-1;
int right = i+1;
while(left>=0 && right<n && s.charAt(left)==s.charAt(right)){
left--;
right++;
ans++;
}
}
for(int i=0;i<n-1;i++){
if(s.charAt(i) == s.charAt(i+1)){
ans++;
int left = i-1;
int right = i+2;
while(left>=0 && right<n && s.charAt(left) == s.charAt(right)){
ans++;
left--;
right++;
}
}
}
return ans;
}
}
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
int maxn = -1;
String ans = "";
for(int center=0;center<2*n-1;center++){
int left = center/2;
int right = left + center%2;
while(left>=0 && right<n && s.charAt(left)==s.charAt(right)){
String tmp = s.substring(left, right+1);
if(tmp.length() > ans.length()) ans = tmp;
left--;
right++;
}
}
return ans;
}
}