标签:style lin vector string public log seq == rom
方法:与substring的不同是这里不需要子串连续
class Solution { public: int longestPalindromeSubseq(string s) { vector<vector<int>> f(s.size(), vector<int>(s.size(), 0)); for(int i=s.size()-1; i>=0; --i) { f[i][i] = 1; for(int j=i+1; j<s.size(); ++j) { if(s[i] == s[j]) f[i][j] = f[i+1][j-1] + 2; else f[i][j] = max(f[i+1][j], f[i][j-1]); } } return f[0][s.size()-1]; } };
或者
class Solution { public: int longestPalindromeSubseq(string s) { vector<vector<int>> f(s.size(), vector<int>(s.size(), 0)); for(int i=0; i<s.size(); ++i) { f[i][i] = 1; for(int j=i-1; j>=0; --j) { if(s[i] == s[j]) f[j][i] = f[j+1][i-1] + 2; else f[j][i] = max(f[j+1][i], f[j][i-1]); } } return f[0][s.size()-1]; } };
Longest Palindromic Subsequence
标签:style lin vector string public log seq == rom
原文地址:http://www.cnblogs.com/chengyuz/p/6750178.html