*0*:

boolean arePermutations(String str1, String str2) { if (str1.length() != str2.length()) { return false; } HashMaphashMapChars = new HashMap (); // enter the chars and the number of times each of them appears for (int i = 0; i < str1.length(); i++) { if (hashMapChars.containsKey(str1.charAt(i))) { int count = hashMapChars.get(str1.charAt(i)); hashMapChars.put(str1.charAt(i), count + 1); } else { hashMapChars.put(str1.charAt(i), 1); } } } // for each char in str2 decrease the value number for (int i = 0; i < str2.length(); i++) { if (hashMapChars.containsKey(str2.charAt(i))) { int count = hashMapChars.get(str2.charAt(i)); count--; if (count < 0) { return false; } hashMapChars.put(str2.charAt(i), count); } else { return false; } } return true; }

Use of an array would be much faster for large strings I think !

ReplyDeleteOr sort them both and compare.

ReplyDeletesorting them both and comparing works if you are allowed to modify the existing strings. Otherwise this method isn't bad.

ReplyDeletewhere is the case where count can be greater than 0 at the end of string 2?

ReplyDeleteWe checked in the first line if the strings are of equal length - so if they are, and none of the counts are below zero, then they shall all be zero.

DeleteThis method gives us O(n) time at the cost of the memory size of a hashmap. Sorting would save us the memory cost, but the fastest sorting algorithm would produce O(nlogn) results. Also the cost of comparing after sorting should be taken into account.

ReplyDelete