Geeks面试题: Longest Palindromic Subsequence
来源:互联网 发布:滴滴架构 知乎 编辑:程序博客网 时间:2024/05/22 19:14
Given a sequence, find the length of the longest palindromic subsequence in it. For example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subseuqnce in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.
The naive solution for this problem is to generate all subsequences of the given sequence and find the longest palindromic subsequence. This solution is exponential in term of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently solved using Dynamic Programming.
注意:
这里是最大子序列的palindromic,不是最大子串的palindromi(leetCode上有道题是)。
最大子序列就是:
1 所选取的字符是原数列的字符
2 字符可以间隔抽去(主要区别,子串是不能有间隔的)
3 字符的顺序不能打乱。
int lpsStrDP(string &s){int n = s.length();vector<vector<int> > ta(n, vector<int>(n));for (int i = 0; i < n; i++){ta[i][i] = 1;}for (int d = 2; d <= n; d++){for (int i = 0; i < n-d+1; i++){int j = i+d-1;if (d==2 && s[i] == s[j])ta[i][j] = 2;else if (s[i] == s[j])ta[i][j] = ta[i+1][j-1] +2;else ta[i][j] = max(ta[i+1][j], ta[i][j-1]);}}return ta[0][n-1];}// Returns the length of the longest palindromic subsequence in seqint lps(char *seq, int i, int j){// Base Case 1: If there is only 1 characterif (i == j)return 1;// Base Case 2: If there are only 2 characters and both are sameif (seq[i] == seq[j] && i + 1 == j)return 2;// If the first and last characters matchif (seq[i] == seq[j])return lps (seq, i+1, j-1) + 2;// If the first and last characters do not matchreturn max( lps(seq, i, j-1), lps(seq, i+1, j) );}int main(){char seq[] = "EEKSFORGEEK";int n = strlen(seq);printf ("The lnegth of the LPS is %d", lps(seq, 0, n));string str = seq;cout<<lpsStrDP(str)<<endl;system("pause");return 0;}
- Geeks面试题: Longest Palindromic Subsequence
- Geeks面试题: Longest Common Subsequence (LCS)
- Geeks 面试题: Longest Bitonic Subsequence
- Geeks面试题: Maximum Sum Increasing Subsequence
- Longest Palindromic Subsequence
- PIQ07: Longest Palindromic Subsequence
- leetcode_middle_42_516. Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- 516 Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- Lettcode_516. Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- 516. Longest Palindromic Subsequence
- leetcod_516. Longest Palindromic Subsequence
- Longest Palindromic Subsequence
- XMUT 1108 雾霾大作战
- Mac OS X的内核
- 变长参数实现
- LeetCode (I)
- 导出Android应用程序数据库。
- Geeks面试题: Longest Palindromic Subsequence
- 无法定位程序输入点FlsGetValue于动态链接库KERNEL32.dll
- 使用Java操作LDAP案例
- 让IO7下的table cell从最左边开始
- 关系数据库的实现
- Oracle的备份操作
- VisualNet图形化的电力综合布线管理系统的应用实例展示
- 人生顿悟之那绝不是人脉
- linux系统监控工具之top命令详解