5.最长回文子串

先来一个比较笨的方法

public class PlalindromeSubStr {

    public static String longestPalindrome(String s) {
        int max = 0;
        int index = 1;
        int startIndex = 0;
        String maxStr = null;
        if (s.length() == 1) {
            return s;
        }
        if (s.length() == 2) {
            if (s.substring(0,1).equals(s.substring(1,2))) {
                return s;
            }
            return s.substring(0,1);
        }

        while (index <= s.length() -1) {
            for (int i = startIndex; i <= index-1; i++){
                String left = null, right = null;
                //子串长度
                int subStrLength = (index-i+1);
                int mid = subStrLength / 2;
                if (subStrLength % 2 == 1){
                    //奇数
                    mid += 1;
                    left = s.substring(i, i+mid-1);
                    right = s.substring(i+mid, index+1);
                } else {
                    //偶数
                    left = s.substring(i, i+mid);
                    right = s.substring(i+mid, index+1);
                }
                //是回文串
                if (isPalindrome(right, left)){
                    String palindrome = s.substring(i, index+1);
                    max = Math.max(palindrome.length(), max);
                    if(max == palindrome.length()){
                        maxStr = palindrome;
                    }
                }
            }
            index++;
        }
        if (null == maxStr){
            return s.substring(0,1);
        } else {
            return maxStr;
        }
    }

    public static Boolean isPalindrome(String s1, String s2) {
        boolean result = true;
        for (int i = 0; i <= s1.length()-1; i++) {
             if (s1.charAt(i) != s2.charAt(s1.length()-1-i)){
                 result = false;
                 break;
             }
        }
        return result;
    }
}

你可能感兴趣的:(算法)