• 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/

                  

  • 相关阅读:
    \r,\n,\r\n的区别
    \r,\n,\r\n的区别
    C# TextBox 换行 滚动到最后一行
    C# TextBox 换行 滚动到最后一行
    C# Textbox 始终保持最后最后一行
    C# Textbox 始终保持最后最后一行
    踩坑之mongodb配置文件修改
    踩坑之mongodb配置文件修改
    开启mongodb 的web
    开启mongodb 的web
  • 原文地址:https://www.cnblogs.com/graph/p/3214058.html
Copyright © 2020-2023  润新知