LeetCode – Valid Anagram (Java)

Given two strings s and t, write a function to determine if t is an anagram of s.

Java Solution 1

Assuming the string contains only lowercase alphabets, here is a simple solution.

public boolean isAnagram(String s, String t) {
    if(s==null || t==null)
        return false;
 
    if(s.length()!=t.length())
        return false;
 
    int[] arr = new int[26];
    for(int i=0; i<s.length(); i++){
        arr[s.charAt(i)-'a']++;
        arr[t.charAt(i)-'a']--;
    }
 
    for(int i: arr){
        if(i!=0)
            return false;
    }
 
    return true;
}

Java Solution 2

If the inputs contain unicode characters, an array with length of 26 is not enough.

public boolean isAnagram(String s, String t) {
    if(s.length()!=t.length())
        return false;
 
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();    
 
    for(int i=0; i<s.length(); i++){
        char c1 = s.charAt(i);
        if(map.containsKey(c1)){
            map.put(c1, map.get(c1)+1);
        }else{
            map.put(c1,1);
        }
    }
 
    for(int i=0; i<s.length(); i++){
        char c2 = t.charAt(i);
        if(map.containsKey(c2)){
            if(map.get(c2)==1){
                map.remove(c2);
            }else{
                map.put(c2, map.get(c2)-1);
            }
        }else{
            return false;
        }    
    }
 
    if(map.size()>0)
        return false;
 
    return true;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Sergio

    “`
    my 2 cents
    public static boolean isAnagramBySum(String s, String t) {
    char[] one = s.toCharArray();
    char[] two = t.toCharArray();
    int sumOne = 0, sumTwo = 0;
    for (int i = 0; i < one.length; i++) {
    sumOne += one[i];
    }
    for (int j = 0; j < two.length; j++) {
    sumTwo += two[j];
    }
    if (sumOne == sumTwo) {
    return true;
    }
    return false;
    }
    “`

  • Hooman

    Second solution wouldn’t work if we have duplicate characters, like “aab” and “ba”. You need to also keep track of key occurrences.