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;
    }
};

發佈了39 篇原創文章 · 獲贊 0 · 訪問量 4869
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章