(UVA) Longest Common Subsequence - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=751&page=show_problem&problem=1346
The solution below used the concept of Longest Common Subsequence, related to Dynamic Programming, to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String s1;
public String s2;
public int[][] memo;
public int rec(int indexS1, int indexS2) {
if (indexS1 == s1.length() || indexS2 == s2.length()) {
return 0;
}
if (memo[indexS1][indexS2] != -1) {
return memo[indexS1][indexS2];
}
int nextS1 = rec(indexS1+1, indexS2);
int nextS2 = rec(indexS1, indexS2+1);
int nextS1S2 = rec(indexS1+1, indexS2+1) + ((s1.charAt(indexS1) == s2.charAt(indexS2)) ? 1 : 0);
memo[indexS1][indexS2] = Math.max(nextS1, Math.max(nextS2, nextS1S2));
return memo[indexS1][indexS2];
}
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
while (line != null) {
s1 = line;
s2 = br.readLine();
memo = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
memo[i][j] = -1;
}
}
bw.write(rec(0, 0)+"\n");
line = br.readLine();
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used the concept of Longest Common Subsequence, related to Dynamic Programming, to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String s1;
public String s2;
public int[][] memo;
public int rec(int indexS1, int indexS2) {
if (indexS1 == s1.length() || indexS2 == s2.length()) {
return 0;
}
if (memo[indexS1][indexS2] != -1) {
return memo[indexS1][indexS2];
}
int nextS1 = rec(indexS1+1, indexS2);
int nextS2 = rec(indexS1, indexS2+1);
int nextS1S2 = rec(indexS1+1, indexS2+1) + ((s1.charAt(indexS1) == s2.charAt(indexS2)) ? 1 : 0);
memo[indexS1][indexS2] = Math.max(nextS1, Math.max(nextS2, nextS1S2));
return memo[indexS1][indexS2];
}
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
while (line != null) {
s1 = line;
s2 = br.readLine();
memo = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
memo[i][j] = -1;
}
}
bw.write(rec(0, 0)+"\n");
line = br.readLine();
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment