[leetcode]Longest Palindromic Substring

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27762917/article/details/79398035

获取最长的回文串

public class Test {
    public static void main(String[] args) {

    }

    public static String longestPalindrome(String s) {
        if (s == null || "".equals(s.replace(" ", "")))
            return "";
        else if (s.length() == 1)
            return s;
        else {
            Map<Integer, String> result = new TreeMap<Integer, String>();
            List<Integer> lengths = new ArrayList<Integer>();
            int length = s.length();
            for (int i = 0; i < s.length(); i++) {
                for (int j = s.length(); j > i; j--) {
                    if (checkPalindrome(s.substring(i, j))) {
                        result.put(s.substring(i, j).length(), s.substring(i, j));
                        lengths.add(s.substring(i, j).length());
                    } else
                        length--;
                }
            }
            Collections.sort(lengths);
            return result.size() == 0 ? "" : result.get(lengths.get(lengths.size() - 1));
        }

    }

    public static boolean checkPalindrome(String s) {
        if (s == null || "".equals(s.replace(" ", "")))
            return false;
        else if (s.length() == 1)
            return true;
        else if(s.length() == 2)
            return s.charAt(0) == s.charAt(1);
        else {
            int length = s.length();
            if (s.length() % 2 == 0) {
                for (int i = 0; i <= s.length() / 2 - 1; i++) {
                    if (s.charAt(i) != s.charAt(length - 1))
                        return false;
                    else {
                        length--;
                    }
                }
                return true;
            } else {
                for (int i = 0; i <= (s.length() - 3) / 2; i++) {
                    if (s.charAt(i) != s.charAt(length - 1))
                        return false;
                    else {
                        length--;
                    }
                }
                return true;
            }
        }
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页