-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Common Sub sequence
40 lines (39 loc) · 1.26 KB
/
Longest Common Sub sequence
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
class Solution {
//Dynamic Programming O(n^2)
public int longestCommonSubsequence(String text1, String text2) {
int n1 = text1.length();
int n2 = text2.length();
if(n1 == 0 || n2 == 0)
return 0;
int[][] ans = new int[n2 + 1][n1 + 1];
for(int i = 0; i < n2 + 1; i++)
ans[i][0] = 0;
for(int i = 0; i < n1 + 1; i++)
ans[0][i] = 0;
for(int i = 0; i < n2; i++)
{
for(int j = 0; j < n1; j++)
{
if(text1.charAt(j) == text2.charAt(i))
{
ans[i + 1][j + 1] = ans[i][j] + 1;
}
else
{
ans[i + 1][j + 1] = Math.max(ans[i][j + 1], ans[i + 1][j]);
}
}
}
return ans[n2][n1];
}
//Recursion O(2^n)
public int longestCommonSubsequence(String text1, String text2, int m, int n)
{
if(m == 0 || n == 0)
return 0;
if(text1.charAt(m) == text2.charAt(n))
return 1 + longestCommonSubsequence(text1, text2, m - 1, n - 1);
else
return longestCommonSubsequence(text1, text2, m, n - 1) + longestCommonSubsequence(text1, text2, m - 1, n);
}
}