-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApril_26_1143_Longest_Common_Subsequence.cpp
46 lines (45 loc) · 1.2 KB
/
April_26_1143_Longest_Common_Subsequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int len=text1.size();
int width=text2.size();
vector<vector<int>> dp(len,vector<int>(width));
for(int i=0;i<len;i++)
{
for(int j=0;j<width;j++)
{
if(text1[i]==text2[j])
{
if(i>0 && j>0)
{
dp[i][j]=1+dp[i-1][j-1];
}
else
{
dp[i][j]=1;
}
}
else
{
if(i>0 && j>0)
{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
else if(i>0)
{
dp[i][j]=dp[i-1][j];
}
else if(j>0)
{
dp[i][j]=dp[i][j-1];
}
else
{
dp[i][j]=0;
}
}
}
}
return dp[len-1][width-1];
}
};