LeetCode

来源:互联网 发布:淘宝服装拍摄后期处理 编辑:程序博客网 时间:2024/06/03 14:44

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

Example 1:
Input:

"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".

Example 2:
Input:

"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".

Subscribe to see which companies asked this question.


题意:求一个字符串中的最长回文子串

思路:dp[i][j]表示字符串下标从 i ~ j 能构成的最长回文子串的长度,最终返回结果为dp[0][len - 1]。


class Solution {public:    int longestPalindromeSubseq(string s) {        int len = s.length();        vector<vector<int>> ans(len + 1, vector<int>(len + 1, 0));        for (int i = 0; i < len; i++) {            ans[i][i] = 1;        }        for (int i = len - 1; i >= 0; i--) {            for (int j = i + 1; j < len; j++) {                if (s[i] == s[j]) {  //相等时说明可以加入当前字符串中                    ans[i][j] = ans[i+1][j-1] + 2;                }                else {  //不等则只能去最大值                    ans[i][j] = max(ans[i+1][j], ans[i][j-1]);                }            }        }        return ans[0][len-1];    }};


0 0
原创粉丝点击