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;
}

3 thoughts on “LeetCode – Valid Anagram (Java)”

  1. seems to me like sorting an array for this will be the best course of action

    this is what I wrote:


    public boolean isAnagram(String s, String t) {

    String strippedFirst = s.replaceAll(" ", "");
    Srtring stippedSecond = t.replaceAll(" ", "");
    if(stripedFirst.length() != stippedSecond.length()) {
    return false;
    }

    char[] sBroken = Arrays.sort(Arrays.toCharArray(stippedFirst)); // ehiisst
    char[] tBroken = Arrays.sort(Arrays.toCharArray(stippedSecond)); //

    for (int i = 0; i < sBroken.length; i++) {
    if (tBroken[i] != sBroken[i]) {
    return false;
    }
    }

    return true;
    }

  2. “`
    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;
    }
    “`

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

Leave a Comment