Skip to content

Commit 361ac46

Browse files
authored
Create longestCommonSubsequence.cpp
1 parent a42832b commit 361ac46

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
3+
4+
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
5+
6+
For example, "ace" is a subsequence of "abcde".
7+
A common subsequence of two strings is a subsequence that is common to both strings.
8+
9+
10+
11+
Example 1:
12+
13+
Input: text1 = "abcde", text2 = "ace"
14+
Output: 3
15+
Explanation: The longest common subsequence is "ace" and its length is 3.
16+
Example 2:
17+
18+
Input: text1 = "abc", text2 = "abc"
19+
Output: 3
20+
Explanation: The longest common subsequence is "abc" and its length is 3.
21+
Example 3:
22+
23+
Input: text1 = "abc", text2 = "def"
24+
Output: 0
25+
Explanation: There is no such common subsequence, so the result is 0.
26+
27+
**/
28+
29+
30+
class Solution {
31+
public:
32+
int longestCommonSubsequence(string text1, string text2) {
33+
int m = text1.size();
34+
int n = text2.size();
35+
// vector<vector<int>> dp(1001, vector<int>(1001));
36+
int dp[1001][1001] = {0};
37+
38+
for(int i = 1; i <= m; ++i) {
39+
for(int j = 1; j <= n; ++j) {
40+
if(text1[i-1] == text2[j-1])
41+
dp[i][j] = 1 + dp[i-1][j-1];
42+
else
43+
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
44+
}
45+
}
46+
return dp[m][n];
47+
}
48+
};

0 commit comments

Comments
 (0)