-1
String str="cat";
char[] arr = new char[26];
for(int i=0; i<str.length(); i++){
    arr[str.charAt(i)-'a']++;
}
String ns = new String(arr);

I came across this piece of code. My doubt is as the array arr is containing \u0000 by default what is this incrementing( arr[str.charAt(i)-'a']++;) operation doing. And how can this arr be converted to a string ns with so many null values in between. sharing the link of full code. The code is running fine. http://www.programcreek.com/2014/04/leetcode-anagrams-java/

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
beginner
  • 9
  • 3
  • 2
    Possible duplicate of [What is the default initialization of an array in Java?](https://stackoverflow.com/questions/3426843/what-is-the-default-initialization-of-an-array-in-java) – BackSlash Jun 10 '17 at 17:11
  • It's a hacky compression of a `Map` for chars in the range a-z – Bohemian Jun 12 '17 at 00:32

2 Answers2

0

The code counts the frequencies of characters of the input string into a char[]. Instead of an int[]. Which sounds counter-intuitive. But this leads to an efficient solution, with some limitations.

The trick is that you can create a String fairly efficiently from a char[], and it will give you the benefits of String.equals. A string created from a char[] that contains character frequencies will not be something readable, but that doesn't matter. Such string will be usable in a hash table, as the linked code does, because String.equals has an implementation that's suitable to use in hash tables.

By contrast, an int[] doesn't have a useful implementation of equals. This is because arrays inherit the implementation of equals from Object, which is not very useful. The consequence of this is that a.equals(b) will return false when a != b, even if they both contain the same values. Thanks to String.equals, new String(a).equals(new String(b)) will return true when a and b are char[], a != b, but they contain the same values. Moreover, there is no way to convert a int[] to something suitable to use in a hash map that would be faster than new String(char[]).

The limitation is that if str contains characters that occur more than 65535 times, then the algorithm will not produce correct output.

janos
  • 120,954
  • 29
  • 226
  • 236
  • have u seen the link i provided . Though it is not converting ns as some readable string but the hashmap is succesfully constructed and u can see by printing the values present in them . that is what i meant by "working fine" – beginner Jun 10 '17 at 17:23
  • @beginner you're right, I read the linked page now, and rewrote my answer – janos Jun 10 '17 at 17:54
0

Try this simple method

static boolean isAnagram(String a, String b) {
    int aSum = a.toUpperCase().chars().sorted().sum();
    int bSum = b.toUpperCase().chars().sorted().sum();        
    if(aSum == bSum)
        return true;
    else
        return false;
}
Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61