最长回文子串
解题思想:动态规划
class Solution { public String longestPalindrome(String s) { int len = s.length(); boolean[][] b = new boolean[len][len]; int max = 0; int begin = 0; for(int i=0;i<len;i++){ for(int j=0;j<=i;j++){ if(s.charAt(i)==s.charAt(j)&&(i-j<=2 || b[j+1][i-1])){ b[j][i] = true; if(i-j+1>max){ max = i - j + 1; begin = j; } } } } return s.substring(begin,begin+max); } }
马拉车算法:
解题思想:中心扩散法
public static String longestPalindrome(String s) { int len = s.length(); if(len == 0) { return ""; } StringBuilder strD = new StringBuilder(); strD.append('*'); for(int i=0;i<len;i++) { strD.append('#'); strD.append(s.charAt(i)); } strD.append('#'); int slen = strD.length(); int[] r = new int[slen]; int mx = 0; int id = 0; int rmax = 0; int meduim = 0; for(int i=0;i<slen;i++) { r[i]= mx>i?Math.min(r[2*id-i],mx-i):1; while(i-r[i]>=0&&i+r[i]<slen&&strD.charAt(i-r[i])==strD.charAt(i+r[i])) { r[i]++; } if(mx<i+r[i]) { mx=i+r[i]; id = i; } if(r[i]>rmax) { rmax = r[i]; meduim = i; } } //return strD.substring(meduim-rmax+1,meduim+rmax).replace("#", ""); int start = (meduim-rmax)/2; return s.substring(start,start+rmax-1); }
参考文献:
马拉车算法:https://blog.csdn.net/Dby_freedom/article/details/93191052