Created
February 17, 2016 04:07
-
-
Save harshadura/e0e0dc6623e3f50a75db to your computer and use it in GitHub Desktop.
Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by harshadura on 2/17/16. | |
*/ | |
public class StringOrder { | |
public static void main(String args[]) { | |
String inputA = "harsha"; | |
String inputB = "sanjeewa"; | |
System.out.println(orderByNSq(inputA.toCharArray(), inputB.toCharArray())); | |
System.out.println(orderByN(inputA.toCharArray(), inputB.toCharArray())); | |
} | |
public static char[] orderByNSq(char[] a, char[] b) { | |
String ret = new String(); | |
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) | |
ret += a[i]; | |
break; | |
} | |
} | |
return ret.toCharArray(); | |
} | |
public static char[] orderByN(char[] a, char[] b) { | |
String ret = new String(); | |
int[] flags = new int[256]; | |
for(int i = 0; i < b.length; i++) | |
flags[b[i]] = 1; | |
for(int j=0; j <a.length; j++) | |
if(flags[a[j]] == 1) { | |
ret += a[j]; | |
flags[a[j]] = 0; | |
} | |
return ret.toCharArray(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment