-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path1143. Longest Common Subsequence
71 lines (61 loc) · 2.05 KB
/
1143. Longest Common Subsequence
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
return helper(text1,text2,0,0);
}
int helper(String s1,String s2,int index1,int index2){
if(index1==s1.length() || index2== s2.length()){
return 0;
}
if(s1.charAt(index1) == s2.charAt(index2)){
return 1 + helper(s1,s2,index1+1,index2+1);
}
return Math.max(helper(s1,s2,index1+1,index2),helper(s1,s2,index1,index2+1));
}
}
class Solution {
int[][] dp;
public int longestCommonSubsequence(String text1, String text2) {
dp = new int[text1.length()][text2.length()];
for(int i=0;i<text1.length();i++){
for(int j=0;j<text2.length();j++){
dp[i][j]=-1;
}
}
return helper(text1,text2,0,0);
}
int helper(String s1,String s2,int index1,int index2){
if(index1==s1.length() || index2== s2.length()){
return 0;
}
if(dp[index1][index2] >=0){
return dp[index1][index2];
}
if(s1.charAt(index1) == s2.charAt(index2)){
dp[index1][index2]= 1 + helper(s1,s2,index1+1,index2+1);
}
else{
dp[index1][index2] = Math.max(helper(s1,s2,index1+1,index2),helper(s1,s2,index1,index2+1));
}
return dp[index1][index2];
}
}
class Solution {
int[][] dp;
public int longestCommonSubsequence(String text1, String text2) {
dp = new int[text1.length()+1][text2.length()+1];
for(int i=0;i<=text1.length();i++){
for(int j=0;j<=text2.length();j++){
if(i==0 || j==0){
continue;
}
if(text1.charAt(i-1)==text2.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}
else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[text1.length()][text2.length()];
}
}