We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent fa38cdc commit b97e547Copy full SHA for b97e547
C++/longest-common-subsequence.cpp
@@ -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