-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1143.Longest Common Subsequence
35 lines (35 loc) · 1.21 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
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
if(text1.isEmpty()||text2.isEmpty()){return 0;}
int a=text1.length();
int b=text2.length();
int dp[][]=new int[a][b];
for(int row[]:dp){Arrays.fill(row,-1);}
return helper(text1,text1.length(),text2,text2.length(),dp);
}
static int helper(String text1,int n,String text2,int m,int[][] dp){
if(n<0||m<0){return 0;}
int curr[]=new int[m+1];
int prev[]=new int[m+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(text1.charAt(i-1)==text2.charAt(j-1)){
curr[j]=1+prev[j-1];
}
else{
int onleft=curr[j-1];
int onright=prev[j];
curr[j]=Math.max(onleft,onright);//i-1][j]
}
}
prev=Arrays.copyOf(curr,m+1);
}
// if(text1.charAt(a)==text2.charAt(b)){
// dp[a][b]= 1+helper(text1,a-1,text2,b-1,dp);
// }
// else{
// dp[a][b]= Math.max(helper(text1,a-1,text2,b,dp),helper(text1,a,text2,b-1,dp));
// }
return curr[m];
}
}