Created
December 20, 2012 06:46
-
-
Save Bekt/4343367 to your computer and use it in GitHub Desktop.
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
//http://coolcodebro.blogspot.com/2012/12/string-permutations.html | |
public class IsPermutation { | |
public static void main(String[] args) { | |
new IsPermutation().run(); | |
} | |
void run() { | |
String a = "12345"; | |
String b = "32541"; | |
System.out.printf("\"%s\" is a perm of \"%s\": %b%n", a, b, isPerm(a, b)); | |
} | |
boolean isPerm(String a, String b) { | |
if(a.length() != b.length()) | |
return false; | |
Map<Character, Integer> aMap = new HashMap<Character, Integer>(); | |
Map<Character, Integer> bMap = new HashMap<Character, Integer>(); | |
for(int i=0; i<a.length(); i++) { | |
char aChar = a.charAt(i); | |
char bChar = b.charAt(i); | |
aMap.put(aChar, getVal(aMap, aChar) + 1); | |
bMap.put(bChar, getVal(bMap, bChar) + 1); | |
} | |
for(int i=0; i<a.length(); i++) { | |
char aChar = a.charAt(i); | |
if(getVal(aMap, aChar) != getVal(bMap, aChar)) | |
return false; | |
} | |
return true; | |
} | |
int getVal(Map<Character, Integer> m, char k) { | |
if(m.get(k) == null) | |
return 0; | |
return m.get(k); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment