leetcod_516. Longest Palindromic Subsequence

题目:

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".

动态规划问题,但是没用动态规划的方法,用了map的方法,存进map然后遍历map,比O(n2)的方法稍微好了一点。但最差也是O(n2)。

想不到如何用动态规划的方法,直接看了别人的解析:

The DP state longest[i][j] means for substring between [i, j] inclusive the longest palindromic subsequence.

Basic cases:
if i == j, then longest[i][j] = 1, naturally
if i+1 == j, then longest[i][j] = 2 if s[i] == s[j]
longest[i][j] = 1 otherwise
Transition rule:

  1. s[i] == s[j]
    dp[i][j] = max(dp[i+1][j], dp[i][j-1], dp[i+1][j-1] + 2)
  2. s[i] != s[j]
    dp[i][j] = max(dp[i+1][j], dp[i][j-1], dp[i+1][j-1])

The condition that only subsequence made it quite simply because at any range [i, j], the s[i], s[j] can be omitted to make the rest range [i+1, j] or [i, j-1] our valid longest palindromic subsequence.

自己的代码:
class Solution {
public:
    int longestPalindromeSubseq(string s) {
        map<char, int> mymap;
        for(int i = 0;i < s.size(); ++i){
            if(mymap.count(s[i]) != 0){
                mymap[s[i]] += 1;
            }
            else mymap[s[i]] = 1;
        }
        map<char, int>::iterator it;
        int max = 0;
        for(it = mymap.begin(); it != mymap.end(); it++){
            if(it->second > max){
                max = it->second;
            }
        }
        return max;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值