LeetCode刷题: 【5】最长回文子串 (动态规划)

1. 题目

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:

输入: "cbbd"
输出: "bb"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


2.思路(动态规划)

(1) 最优子问题
  • 如果一个子串s(i, j)是回文串,则s(i+1, j-1)一定是回文,并且s(i)==s(j)
  • (i+1)>=(j-1),则s(i, j)是回文串;
(2) 状态转移公式
  • f(i,j) = f(i+1,j-1) && s(i) == s(j)

3. c++代码

#include<iostream>
#include<cstring>
using namespace std;

class Solution {
    
    
private:
    bool temp[1001][1000];  // 解空间:表示s(i,j)是否是回文
    int maxS[2];			// 最优解 0:始位置(i) 1:步距(step = j - 1) 
public:
    string longestPalindrome(string s) {
    
    
        // 初始化对角线
        for(int i = 0; i < s.length(); i++){
    
    
            temp[i][i] = true;
            temp[i + 1][i] = true;
        }
        maxS[0] = 0;
        maxS[1] = 0;
        // f(i,j) = f(i+1,j-1) && s(i) == s(j)
        // j = i + step
        for(int step = 1; step <= s.length(); step++){
    
    
            for(int i = 0; i < s.length() - step; i++){
    
    
                int j = i + step;
                // cout<<i<<","<<j<<endl;
                temp[i][j] = temp[i+1][j-1] && s[i] == s[j];
                if(temp[i][j] && step > maxS[1]){
    
    
                    maxS[0] = i;
                    maxS[1] = step;
                }
            }
        }

        // show(s.length());

        return s.substr(maxS[0], maxS[1] + 1); // substr不包括最后的元素
    }
/*
    void show(int n){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                cout<<temp[i][j]<<"\t";
            }
            cout<<endl;
        }
    }*/
};

int main(){
    
    

    Solution s;
    // 测试用例
    string str("anugnxshgonmqydttcvmtsoaprxnhpmpovdolbidqiyqubirkvhwppcdyeouvgedccipsvnobrccbndzjdbgxkzdbcjsjjovnhpnbkurxqfupiprpbiwqdnwaqvjbqoaqzkqgdxkfczdkznqxvupdmnyiidqpnbvgjraszbvvztpapxmomnghfaywkzlrupvjpcvascgvstqmvuveiiixjmdofdwyvhgkydrnfuojhzulhobyhtsxmcovwmamjwljioevhafdlpjpmqstguqhrhvsdvinphejfbdvrvabthpyyphyqharjvzriosrdnwmaxtgriivdqlmugtagvsoylqfwhjpmjxcysfujdvcqovxabjdbvyvembfpahvyoybdhweikcgnzrdqlzusgoobysfmlzifwjzlazuepimhbgkrfimmemhayxeqxynewcnynmgyjcwrpqnayvxoebgyjusppfpsfeonfwnbsdonucaipoafavmlrrlplnnbsaghbawooabsjndqnvruuwvllpvvhuepmqtprgktnwxmflmmbifbbsfthbeafseqrgwnwjxkkcqgbucwusjdipxuekanzwimuizqynaxrvicyzjhulqjshtsqswehnozehmbsdmacciflcgsrlyhjukpvosptmsjfteoimtewkrivdllqiotvtrubgkfcacvgqzxjmhmmqlikrtfrurltgtcreafcgisjpvasiwmhcofqkcteudgjoqqmtucnwcocsoiqtfuoazxdayricnmwcg");

    cout<<endl<<s.longestPalindrome(str)<<endl<<endl;
    while(str != "000"){
    
    
        cin>>str;
        cout<<"---------------------"<<endl<<s.longestPalindrome(str)<<endl<<endl;
    }

    return 0;
}

4. 小记

  • 一开始的时候为了节省空间想要使用map<int, map<int, bool> >来进行存储,但结果运行超时,因为c++中map使用红黑树实现,当问题规模变大,查询速度会下降。
  • cout的输出速度很慢,在输出n=1000的问题空间时要花上数分钟

猜你喜欢

转载自blog.csdn.net/Activity_Time/article/details/103902458