(UVA) String to Palindrome - Solution 1
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1680
The solution below used Dynamic Programming to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String s;
public int[][] memo;
public int rec(int left, int right) {
if (left >= right) {
return 0;
}
if (memo[left][right] != -1) {
return memo[left][right];
}
int min = Integer.MAX_VALUE;
min = Math.min(min, rec(left, right-1) + 1); // insert left
min = Math.min(min, rec(left+1, right) + 1); // delete left
min = Math.min(min, rec(left+1, right-1) + ((s.charAt(left) == s.charAt(right)) ? 0 : 1)); // replace
memo[left][right] = min;
return memo[left][right];
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
memo = new int[1024][1024];
for (int test = 0; test < numTests; test++) {
s = sc.next();
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
memo[i][j] = -1;
}
}
bw.write("Case " + (test+1) + ": ");
bw.write(rec(0, s.length()-1)+"\n");
}
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 Dynamic Programming to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String s;
public int[][] memo;
public int rec(int left, int right) {
if (left >= right) {
return 0;
}
if (memo[left][right] != -1) {
return memo[left][right];
}
int min = Integer.MAX_VALUE;
min = Math.min(min, rec(left, right-1) + 1); // insert left
min = Math.min(min, rec(left+1, right) + 1); // delete left
min = Math.min(min, rec(left+1, right-1) + ((s.charAt(left) == s.charAt(right)) ? 0 : 1)); // replace
memo[left][right] = min;
return memo[left][right];
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
memo = new int[1024][1024];
for (int test = 0; test < numTests; test++) {
s = sc.next();
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
memo[i][j] = -1;
}
}
bw.write("Case " + (test+1) + ": ");
bw.write(rec(0, s.length()-1)+"\n");
}
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