手撸代码-最长回文字符串

求最长回文字符串

思路一:动态规划

  • 回文字符串的最大长度是n,最小长度是1
  • 对于1~n的每个长度k,从左到右遍历字符串,判断每个长度为k的子字符串是否是回文字符串
  • 长度为k的字符串(左右边界是i,i+k)是否为回文字符串依赖于字符串(i+1,i+k-1)是否是回文字符串
  • 长度为1的字符串肯定是回文字符串
public int getLongestPalindrome(String A, int n) {
    
    
        // write code here
        boolean[][] isPal = new boolean[n][n];
        int c = 0;
        int max = 0;
        for(; c <= n - 1; c++) {
    
    
            for (int i = 0; i < n - c; i++) {
    
    
                int j = i + c;
                if (A.charAt(i) == A.charAt(j)) {
    
    
                    // 在两个字符相等的前提下,如果c=1,字符串长度为2,一定是回文字符串
                    if (c <= 1) {
    
    
                        isPal[i][j] = true;
                    } else {
    
    
                        isPal[i][j] = isPal[i+1][j-1];
                    }
                    
                    if (isPal[i][j]) {
    
    
                        max = c + 1;
                    }
                }
            }
        }
        
        return max;
    }

猜你喜欢

转载自blog.csdn.net/epitomizelu/article/details/120027694
今日推荐