Skip to content

Commit b97e547

Browse files
authored
Create longest-common-subsequence.cpp
1 parent fa38cdc commit b97e547

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

C++/longest-common-subsequence.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(m * n)
2+
// Space: O(min(m, n))
3+
4+
class Solution {
5+
public:
6+
int longestCommonSubsequence(string text1, string text2) {
7+
if (text1.size() < text2.size()) {
8+
return longestCommonSubsequence(text2, text1);
9+
}
10+
vector<vector<int>> dp(2, vector<int>(text2.size() + 1));
11+
for (int i = 1; i <= text1.size(); ++i) {
12+
for (int j = 1; j <= text2.size(); ++j) {
13+
dp[i % 2][j] = (text1[i - 1] == text2[j - 1])
14+
? dp[(i - 1) % 2][j - 1] + 1
15+
: max(dp[(i - 1) % 2][j], dp[i % 2][j - 1]);
16+
17+
}
18+
}
19+
return dp[text1.size() % 2][text2.size()];
20+
}
21+
};

0 commit comments

Comments
 (0)