How to compare two lines If they are rearranged

I wanted to know how I can compare two rearranged strings. For example, if String a = "string", String b = "tsrngi" ... If I compare a.equals (b), it will return false due to character order .. I want it to return true because the characters are the same but only the order is different. Thanks.

+4
source share
2 answers

Sort them, then compare. To sort, use something like:

char[] content = unsorted.toCharArray(); java.util.Arrays.sort(content); String sorted = new String(content); 
+8
source

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; 
+6
source

All Articles