LeetCode(5):Longest Palindromic Substring

Longest Palindromic Substring:Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

题意:求最长回文字串。

思路:可以选择一个字符以其为中心向两边扩展,扩展的过程中判断是否是回文;也可以使用动态规划的方法参考博文写的比较清楚。

代码:

public class Solution {
    public String longestPalindrome(String s) {
        if(s.length()==0) return "";
            if(s.length()==1) return s;
            String res = "";
            int maxLen =0;
            boolean[][] palin = new boolean[s.length()][s.length()];
            
            StringBuilder sb =new StringBuilder();
            for(int i=s.length()-1;i>=0;i--){
                for(int j=i;j<s.length();j++){
                    if(s.charAt(i)==s.charAt(j)&&(j-i<=2||palin[i+1][j-1])){
                        palin[i][j] = true;
                        if(maxLen<j-i+1){
                            maxLen = j-i + 1;
                            res = s.substring(i, j+1);
                        }
                    }
                }
                
            }
            return res;
    }
}
posted @ 2016-03-08 19:47  Lewisr  阅读(106)  评论(0编辑  收藏  举报