[Java] ACM CommonPermutationQ
The Problem
Given two strings a and b, print the longest string x of letters such that there is apermutation of x that is a subsequence of a and there is a permutation of x that is a
subsequence of b.
Sanple Input / Output
source code
import java.util.Scanner;
import java.util.Arrays;
/**
*
* @author http://www.javaagkasit.blogspot.com/
*/
public class CommonPermutation {
int[] d = new int[1000];
static String strtemp;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
CommonPermutation cp = new CommonPermutation();
while (true) {
String[] a = (sc.nextLine()).split("");
String[] b = (sc.nextLine()).split("");
if (a.length <= 1000 | b.length <= 1000) {
int c = 0;
char[] out = new char[a.length];
for (int i = 1; i < a.length; i++) {
for (int j = 1; j < b.length; j++) {
if (cp.check(j) == false) { //not in store index
if (a[i].equals(b[j])) { //if chalacter
s1[i] == s2[j]
out[c++] = b[j].charAt(0);//then store output
cp.store(j); //then store index
break; //then stop Search
}
} else {
continue;
}
}
}
cp.printout(out, c);//print output
cp.clearArr(); //clear arrays store index
System.out.println();
}
}
}
public boolean check(int i) {
boolean c = true;
int m = Arrays.binarySearch(d, i);
if (m < 0) {
c = false;
}
return c;
}
public void printout(char[] s, int c) {
char[] ans = new char[c];
for (int i = 0; i < ans.length; i++) {
ans[i] = s[i];
}
Arrays.sort(ans);
System.out.print(ans);
}
public void store(int p) {
int c = 0;
d[c++] = p;
Arrays.sort(d);
}
public void clearArr() {
for (int i = 0; i < d.length; i++) {
d[i] = 0;
}
}
}