• [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 
        }
    }
  • 相关阅读:
    关于quartusII 错误 Error: Current license file does not support the EP*** device 错误原因总结
    怎样用delphi关闭并重新启动 explorer.exe进程
    SQL创建链接服务器
    C#服务启动以及服务指令
    底部广告弹出
    选项卡
    tab切换
    pagex/y offsetx/y screenx/y clientx/y 用法及区别
    放大镜jQuery效果
    放大镜js实现效果
  • 原文地址:https://www.cnblogs.com/airwindow/p/4193302.html
Copyright © 2020-2023  润新知