[UVa OJ] Longest Common Subsequence

简介: This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (see here).

This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (see here).

My accepted code is as follows.

 

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 int lcs(string s, string t) {
 8     int m = s.length(), n = t.length();
 9     vector<int> cur(m + 1, 0);
10     for (int j = 1; j <= n; j++) {
11         int pre = 0;
12         for (int i = 1; i <= m; i++) {
13             int temp = cur[i];
14             cur[i] = (s[i - 1] == t[j - 1] ? pre + 1 : max(cur[i], cur[i - 1]));
15             pre = temp;
16         }
17     }
18     return cur[m];
19 }
20 
21 int main(void) {
22     string s, t;
23     while (getline(cin, s)) {
24         getline(cin, t);
25         printf("%d\n", lcs(s, t));
26     }
27     return 0;
28 }

 

Well, try this problem here and get Accepted :)

目录
相关文章
|
6月前
|
人工智能
HDU-1159-Common Subsequence
HDU-1159-Common Subsequence
33 0
|
6月前
poj-1458-Common Subsequence
poj-1458-Common Subsequence
30 0
|
6月前
|
C++ 容器
POJ3096—Surprising Strings
POJ3096—Surprising Strings
|
人工智能 BI
UVA live 2678 - Subsequence
关于这个题目,有多种的解法,如果枚举起点和终点,时间复杂度为O(n^3),但如果我们用一个数组B把一段数的和存起来,B[i] = sum(a[1].....a[i])。这样就可以把时间复杂度降到O(n^2)。
69 0
|
算法
POJ3061 Subsequence
POJ3061 Subsequence
|
索引
LeetCode 392. Is Subsequence
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
101 0
LeetCode 392. Is Subsequence
LeetCode 376. Wiggle Subsequence
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
96 0
LeetCode 376. Wiggle Subsequence
HDU 4632 Palindrome subsequence(动态规划)
HDU 4632 Palindrome subsequence(动态规划)
74 0
HDU 4632 Palindrome subsequence(动态规划)
POJ-1458,Common Subsequence(经典DP)
POJ-1458,Common Subsequence(经典DP)
|
人工智能
POJ 2533 Longest Ordered Subsequence
POJ 2533 Longest Ordered Subsequence
107 0