Simple Java Solution 4ms with one array


  • 0
    J
    public class Solution {
        public boolean isAnagram(String s, String t) {
            if (s == null || t == null || (s.length() != t.length())) {
                return false;
            }
            int[] checker = new int[128];
            for (char c : s.toCharArray()) {
                checker[c]++;        }
            for (char c : t.toCharArray()) {
                checker[c]--;
            }
            for (int x : checker) {
                if (x != 0) {
            return false;
                }
            }
            return true;
        }
    }

  • 0
    K

    We could return false when --check[c] < 0. Then we reduce one for loop.

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

Log in to reply
 

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