最长回文子串
最长回文子串,比较常考的一道算法题,主要用来练习动态规划 可以直接复制下面的代码去自己的IDE
package com.wy.string;
public class LongestPalindrome {
public static void main(String[] args) {
String str = "123abcba?";
System.out.println(getLongestPalindrome1(str));
}
public static int getLongestPalindrome1(String str){
if(str.length() == 1) return 0;
char[] chars = str.toCharArray();
int[][] dp = new int[str.length()][str.length()];
int maxlength = 0;
for (int i = str.length() - 1; i >= 0; i--) {
for (int j = i; j < str.length(); j++) {
if(chars[i] == chars[j]){
if(j - i <= 2){
dp[i][j] = 1;
}else{
dp[i][j] = dp[i + 1][j - 1];
}
}
if(dp[i][j] == 1)
maxlength = Math.max(maxlength, j - i + 1);
}
}
return maxlength;
}
public int getLongestPalindrome2(String A, int n) {
if(n < 2) {
return n;
}
int res = 0;
for(int i = 0; i < n; i++) {
int len = Math.max(helper(A, i, i), helper(A, i, i + 1));
res = Math.max(res, len);
}
return res;
}
public int helper(String A, int left, int right) {
while(left >= 0 && right < A.length()) {
if(A.charAt(left) == A.charAt(right)) {
left--;
right++;
continue;
}
break;
}
return right - left + 1 - 2;
}
}
参考链接
|