• 5. Longest Palindromic Substring


    Problem statement

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

    Example:

    Input: "babad"
    
    Output: "bab"
    
    Note: "aba" is also a valid answer.

    Example:

    Input: "cbbd"
    
    Output: "bb"

    Solution: DP

    Compare with 516. Longest Palindromic Subsequence, the difference is the subsequence and substring, subsequence does not require all the palindrome is in a row, however, substring must be a consective string. The dynamic programming formula is a little bit different.

    dp[i][j] meas s(i, j) is a palindrome or not, if it is the length is j - i + 1;

    dp[i][j] is true only s[i] == s[j] and dp[i + 1][j - 1] also is true, or i and j is consective or there is only one element between i and j --> j - i <= 2.

    Each time find a palindrome,  we should compare the length with previous one and update if necessary.

    Time complexity is O(n * n), space complexity is O(n * n).

    class Solution {
    public:
        string longestPalindrome(string s) {
            if(s.empty()){
                return "";
            }
            int size = s.size();
            int dp[size][size] = {};
            string ans("");
            for(int i = size - 1; i >= 0; i--){
                for(int j = i; j < size; j++){
                    if(s[i] == s[j] && (j - i < 3 || dp[i + 1][j - 1])){
                        dp[i][j] = 1;
                        if(ans.empty() || j - i + 1 > ans.size()){
                            ans = s.substr(i, j - i + 1);
                        }
                    }
                }
            }
            return ans;
        }
    };

    This is the same solution, but we do DP from a different directions.

    class Solution {
    public:
        string longestPalindrome(string s) {
            if(s.empty()){
                return "";
            }
            int size = s.size();
            int dp[size][size] = {0};
            string ans; 
            for(int i = 0; i < size; i++){
                for(int j = 0; j <= i; j++){
                    if(s[j] == s[i] && (i - j <= 2 || dp[j + 1][i - 1])){
                        dp[j][i] = 1;
                        if(ans.empty() || i - j + 1 > ans.size()){
                            ans = s.substr(j, i - j + 1);
                        }
                    }
                }
            }
            return ans;
        }
    };
  • 相关阅读:
    Hadoop添加节点的方法
    CSS中如何实现DIV居中
    Python新手入门教程,从环境准备到掌握基本编程
    八、使用pull解析器操作xml文件
    九、使用SharedPreferences进行数据存储
    十八、发送xml数据给服务器
    四、对应用进行单元测试
    二、短信发送器
    一、电话拨号器
    十四、ContentProvider往通讯录添加联系人和获取联系人
  • 原文地址:https://www.cnblogs.com/wdw828/p/6829000.html
Copyright © 2020-2023  润新知