zoukankan      html  css  js  c++  java
  • [LeetCode#5]Longest Palindromic Substring

    The problem: (The code of dynamic programming is very concise and elegant. You must learn it!)

    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.

    My analysis:

    The problem could be perfectly solved by using dynamic programming. 

    The state transformaion equation is clear, and could be divided into following kinds :

    assume: p[i][j] indicate whether the string from position i to position j is a palindromic. 

    we could have following state transistion fuction:

    1. p[i][j] == true; iff i = j
    2. p[i][j] = s[i] == s[j]; iff j = i+1
    3. p[i][j] = s[i][j] && p[i+1][j-1]; iff j > i + 1

    My solution: 

     
    /*
    The state trasition at here:
    p[i][j] == true; iff i = j
    p[i][j] = s[i] == s[j]; iff j = i+1 
    p[i][j] = s[i][j] && p[i+1][j-1]; iff j > i + 1  
    */
    
    public class Solution {
        public String longestPalindrome(String s) {
            if (s.length() == 0 || s.length() == 1)
                return s;
    
            char[] s_Array = s.toCharArray(); 
            int len = s.length();
            int max_len = 0;
            int max_front = 0;
            int max_end = 0;
            boolean[][] pa_matrix = new boolean[len][len]; //the initial value of boolean type is false
            
            for (int i = 0; i < len; i++) {  //note: i is the index for end, j is the index for front 
                for (int j = 0; j <= i; j++) { //compute and memorize the pa_matrix from the bottom to up
                        if (i == j)
                            pa_matrix[i][j] = true;
                        if ((i == j + 1) && (s_Array[i] == s_Array[j]))
                            pa_matrix[i][j] = true;
                        if ((i > j + 1) && pa_matrix[i - 1][j + 1] && (s_Array[i] == s_Array[j])) //don't miss condition
                            pa_matrix[i][j] = true;
                            
                        if ((pa_matrix[i][j] == true) && (i - j + 1 > max_len)) {
                            max_len = i - j + 1;
                            max_front = j;
                            max_end = i;
                        }
                }           
            }
            return s.substring(max_front, max_end + 1); //take care of the usage of String.subString ... index 
        }
    }
  • 相关阅读:
    bzoj1083: [SCOI2005]繁忙的都市 瓶颈生成树
    Codeforces Round #344 (Div. 2)C. Report
    Wannafly挑战赛14E无效位置
    Codeforces Round #378 (Div. 2)F
    1059: [ZJOI2007]矩阵游戏 二分图匹配
    Educational Codeforces Round 42 (Rated for Div. 2)F
    bzo1016: [JSOI2008]最小生成树计数
    bzoj1009: [HNOI2008]GT考试 ac自动机+矩阵快速幂
    bzoj1070: [SCOI2007]修车
    table表格frame属性
  • 原文地址:https://www.cnblogs.com/airwindow/p/4193302.html
Copyright © 2011-2022 走看看