• LeetCode_Longest Palindromic Substring


    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.
    

      分析:   DP 问题

    Initial state:
    table[i][i] =  true.
    table[i][i+1] = (s[i]==s[i+1]);

    State Change:
    if s[i]==s[j], table[i][j]=table[i+1][j-1]

    class Solution {
    public:
        string longestPalindrome(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int n = s.size();
            if(n < 2) return s;
            vector<vector<bool>> table(n, vector<bool>(n,false));
            
            //init length 1
            for(int i = 0; i< n; i++)
                 table[i][i] = true;
                 
            int len, maxlen = 1, maxStart = 0,i,j;
            for(len = 2; len <= n ; len ++)
            {
               for(i = 0; i< n - len +1 ; i++)
               { 
                   j = i + len - 1;
               
                  if(s[i] == s[j] &&len == 2)
                    {
                          table[i][j] = true;
                         maxlen = len;
                         maxStart = i;
                    }
                         
                   else if (s[i] == s[j] && table[i+1][j-1])
                    {
                        table[i][j] = true;
                        maxlen = len;
                        maxStart = i;
                    }
                    
               }
            }
            
               
            return s.substr(maxStart , maxlen);
        }
    };

    这里解释下为什么len ==2 要单独处理: 因为table[i][j]只有上三角的值有意义,即 j >= i ; 当len = 2 时,table[i+1][j-1] j-1= i+2-1-1 = i  即此时j-1< i+1 ; 所以要单独处理

    reference :http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html

                   http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/

                  

  • 相关阅读:
    elasticsearch(一):JAVA api操作
    elasticsearch(一):安装与配置
    Apache POI导出excel
    Java实现验证码
    Java数据库连接池原理与简易实现
    SpringMvc注解开发
    类型转换的时候,.valueOf()和.parseX(),.Xvalue()的区别
    kmp算法模板
    java 的任意进制间转换(很方便)
    海伦-秦九韶公式(利用三角形的三边求面积)
  • 原文地址:https://www.cnblogs.com/graph/p/3214058.html
Copyright © 2020-2023  润新知