My Java Solution (8ms)


  • 8
    A

    public class Solution {

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

    }


  • 0
    C

    Good Solution considering the fact that the strings will contain only lower case characters.


  • 0
    S

    I think there is no need to write:
    for(int i = 0; i< 26; i++) {
    alphabet[i] = 0;
    }
    because every element in alphabet is zero when:
    int[] alphabet = new int[26];


  • 0
    L

    the time complexity is O(s.lenfth+t.length),but yours use 8ms too long....the sort just 6ms...and mine same to you is 4ms....not need to "-'a'" and Initialization to zero...just use 257 array size..


  • 0
    D

    What if the test case is s: "aaaaaaaabb" t:"ab" ?


  • 0
    B

    code "if (s.length() != t.length() ) return false;" will handle this case


  • 0
    R

    That's a neat solution. Do you know how you would adapt it if there were unicode characters too?

    I'm asking since I have no idea. Thanks.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.