中心扩展法(最长回文串)
public class LongestPalindrome {
public static void main(String[] args) {
LongestPalindrome longestPalindrome = new LongestPalindrome();
System.out.println(longestPalindrome.longestPalindrome("abdbdc"));
}
// 判断是否是回文串
public boolean isMatch(String s) {
int len = s.length();
for (int i = 0; i < len / 2; i++) {
// 根据中心判断是否相等
if (s.charAt(i) != s.charAt(len - i - 1)) {
return false;
}
}
return true;
}
public String longestPalindrome(String s) {
String result = "";
int max = 0;
int len = s.length();
for (int i = 0; i < len; i++)
for (int j = i + 1; j <= len; j++) {
// 判断每一段子串
String str = s.substring(i, j);
if (isMatch(str) && str.length() > max) {
result = s.substring(i, j);
// 记录回文串的最大长度
max = Math.max(max, result.length());
}
}
return result;
}
}
KMP算法
next数组
字符串最长的公共前后缀
public static void getNextArr(int[] next, String s) {
int j = 0;//j表示前缀起始位置
next[0] = 0;
//i表示后缀起始位置
for(int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = next[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
j++;
}
next[i] = j;
}
}
匹配
public static int getIndexOf(String haystack, String needle) {
if (haystack == null){
return -1;
}
if (needle == null || needle.length() == 0) {
return -1;
}
int[] next = new int[needle.length()];
getNextArr(next, needle);
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;
}