NC_17_getLongestPalindrome

package org.example.interview.practice;

/**
 * @author xianzhe.ma
 * @date 2021/9/3
 */

public class NC_17_getLongestPalindrome {

    public static int getLongestPalindrome(String A, int n) {
        // write code here
        if (n < 2)
            return A.length();
        //start表示最长回文串开始的位置,
        //maxLen表示最长回文串的长度
        int maxLen = 1;
        boolean[][] dp = new boolean[n][n];
        for (int right = 1; right < n; right++) {
            for (int left = 0; left <= right; left++) {
                //如果两种字符不相同,肯定不能构成回文子串
                if (A.charAt(left) != A.charAt(right))
                    continue;

                //下面是s.charAt(left)和s.charAt(right)两个
                //字符相同情况下的判断
                //如果只有一个字符,肯定是回文子串
                if (right == left) {
                    dp[left][right] = true;
                } else if (right - left <= 2) {
                    //类似于"aa"和"aba",也是回文子串
                    dp[left][right] = true;
                } else {
                    //类似于"a******a",要判断他是否是回文子串,只需要
                    //判断"******"是否是回文子串即可
                    dp[left][right] = dp[left + 1][right - 1];
                }
                //如果字符串从left到right是回文子串,只需要保存最长的即可
                if (dp[left][right] && right - left + 1 > maxLen) {
                    maxLen = right - left + 1;
                }
            }
        }
        //最长的回文子串
        return maxLen;
    }

    public static int getLongestPalindrome(String input) {
        int length = input.length();
        boolean[][] dp = new boolean[length][length];
        int maxLen = 1;
        for (int right = 1;right < length;right++) {
            for (int left = 0;left <= right;left ++) {
                if (input.charAt(right) != input.charAt(left)) {
                    continue;
                }

                if (left == right) {
                    dp[left][right] = true;
                } else if (right - left <= 2) {
                    dp[left][right] = true;
                } else {
                    dp[left][right] = dp[left+1][right-1];
                }

                //如果字符串从left到right是回文子串,只需要保存最长的即可
                if (dp[left][right] && right - left + 1 > maxLen) {
                    maxLen = right - left + 1;
                }
            }
        }

        return maxLen;
    }

    public static void main (String[] args) {
        String str = "baabccc";
//        System.out.println(getLongestPalindrome(str, 7));
        System.out.println(getLongestPalindrome(str));
    }
}

 

posted on 2022-02-10 15:52  MaXianZhe  阅读(38)  评论(0编辑  收藏  举报

导航