-
Notifications
You must be signed in to change notification settings - Fork 0
/
LCS of three strings.txt
50 lines (49 loc) · 1.34 KB
/
LCS of three strings.txt
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
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb=new StringBuffer();
int T=Integer.parseInt(br.readLine());
while(T-->0)
{
String[] s=br.readLine().split("\\s");
int a=Integer.parseInt(s[0]);
int b=Integer.parseInt(s[1]);
int c=Integer.parseInt(s[2]);
s=br.readLine().split("\\s");
char[] c1=s[0].toCharArray();
char[] c2=s[1].toCharArray();
char[] c3=s[2].toCharArray();
int[][][] dp=new int[a][b][c];
for(int[][] x:dp)
{
for(int[] y:x)
{
Arrays.fill(y,-1);
}
}
sb.append(lcs(c1,c2,c3,a-1,b-1,c-1,dp)+"\n");
}
System.out.print(sb);
}
public static int lcs(char[] c1,char[] c2,char[] c3,int i,int j,int k,int[][][] dp)
{
if(i==-1 || j==-1 || k==-1)
{
return 0;
}
if(dp[i][j][k]!=-1)
{
return dp[i][j][k];
}
if(c1[i]==c2[j] && c2[j]==c3[k])
{
return dp[i][j][k]=lcs(c1,c2,c3,i-1,j-1,k-1,dp)+1;
}
return dp[i][j][k]=Math.max(lcs(c1,c2,c3,i-1,j,k,dp),Math.max(lcs(c1,c2,c3,i,j-1,k,dp),lcs(c1,c2,c3,i,j,k-1,dp)));
}
}