I really like the JRL solution, as it is pretty elegant. At the same time, I feel that since there is a solution that is an order of magnitude better, I have to share it. This is less elegant, but it is O(n) instead of O(n lg n) .
if(str1.length() != str2.length()) return false; Map<Character, Integer> counts = new HashMap<Character, Integer>(); for(int i = 0; i < str1.length(); i++) { // add 1 for count for str1 if(counts.contains(str1.charAt(i)) { counts.put(str1.charAt(i),counts.get(star1.charAt(i)) + 1); } else { counts.put(str1.charAt(i),1); } // sub 1 for count for str2 if(counts.contains(str2.charAt(i)) { counts.put(str2.charAt(i),counts.get(str2.charAt(i)) - 1); } else { counts.put(str2.charAt(i),-1); } } // when you're done, all values in the map should be 0. If they // aren't all 0, you don't have equal-arranged strings. for(Integer i : counts.values()) { if(i.intValue() != 0) return false; } // we made it this far, we know it true return true;
source share