Simple Java 4ms solution


  • 12
    C
    public class Solution {
        public boolean isAnagram(String s, String t) {
            if (s.length() != t.length()) return false;
            char[] cs = s.toCharArray();
            char[] ct = t.toCharArray();
            int[] map = new int[127];
            int count = 0;
            for (int i = 0; i < cs.length; i++) {
                if(++map[cs[i]] == 1) count ++;
                if(--map[ct[i]] == 0) count --;
            }
            return count == 0;
        }
    }

  • 0
    C

    Your algorithm is the fatest I’ve ever seen in this problem before!
    But I think this trick will reduce a little bit space consumption. Thank you for your brilliant idea!

    if (s.length() != t.length()) return false;
            char[] cs = s.toCharArray();
            char[] ct = t.toCharArray();
            int[] map = new int[26];
            int count = 0;
            for (int i = 0; i < cs.length; i++) {
                if(++map[cs[i]-'a'] == 1) count ++;
                if(--map[ct[i]-'a'] == 0) count --;
            }
            return count == 0;

Log in to reply
 

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