public class GoogleQuestion { public static void main(String args[]) { String a = "AMITABH BACHCHAN"; String b = "RAJNIKANTH"; System.out.println("First String is :"+a); System.out.println("Second String is :"+b); System.out.println(getCommonCharNSquard(a.toCharArray(), b.toCharArray())); System.out.println(getCommonCharN(a.toCharArray(), b.toCharArray())); } public static char[] getCommonCharNSquard(char[] a, char[] b) { String ret =""; for(int i = 0; i < a.length; i++) for(int j=0; j <b.length; j++) { if(a[i] == b[j]) { if(ret.indexOf(a[i]) == -1) // if not previously , then add else dont add // ret is empty(nothing), so comparing it with a[i], which now contains intersection // of a,b and it with indexof(-1), as it is empty so automatically all values copies here. ret += a[i]; break; // it may reduce the processing time, but still n*n } } return ret.toCharArray(); } public static char[] getCommonCharN(char[] a, char[] b) { String ret = new String(); boolean[] flags = new boolean[256]; //sizeOf(char)=256 for(int i = 0; i < b.length; i++) flags[b[i]] = true; for(int j=0; j <a.length; j++) if(flags[a[j]] == true) { ret += a[j]; // order of a flags[a[j]] = false; // avoids repeation only.. } return ret.toCharArray(); } }
Home » Strings(We Suck Every1) » GoogleQuestion