给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba"也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
分析:可以看出是动态规划的题。
(1)设置数组flag[length][length],flag[i][j]表示string的第i位到第j位是不是回文串。
(2)可知当i等于j的时候肯定是回文的,如"a"
(3)由此可以发现i到i+1如子串“aa”是回文的。
(4)有这个规则后我们就可以从i到i+2(2到n)开始进行比较了。 因为 i到i+2如果是回文的条件是char(i)==char(i+2),然后中间的char(i+1)==char(i+1)
那其实是要char(i+1)==char(j-1)。此时j是i+2。
import java.util.HashMap; import java.util.Map; public class Main { public Main() { // TODO Auto-generated constructor stub } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.longestPalindrome("ccc")); } } class Solution { public String longestPalindrome(String s) { if (null == s || "".equals(s)) { return null; } int stringLength = s.length(); boolean[][] flag = new boolean[stringLength][stringLength]; int start = 0; int maxLength = 0; for(int i=0;i<stringLength;++i) { flag[i][i]=true; if(i+1<stringLength&&s.charAt(i)==s.charAt(i+1)) { flag[i][i+1]=true; maxLength=1; start=i; } } for (int step = 2; step < stringLength; ++step) { for (int i = 0; i < stringLength; ++i) { int j = i + step ; if (j >= stringLength) { break; } if (flag[i + 1][j - 1] && s.charAt(i) == s.charAt(j)) { flag[i][j] = true; start = i; maxLength = j - i ; } } } return s.substring(start, start + maxLength+1); } }