242. Vaild anagram

https://leetcode.com/problems/valid-anagram/

Given two strings s and t, return true if t is an anagram of s__, and__ false __otherwise__. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1: Input: s = “anagram”, t = “nagaram” Output: true Example 2: Input: s = “rat”, t = “car” Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104 	
s and t consist of lowercase English letters.

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

  • code
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] count = new int[26];
        
        if (s.length() != t.length()) return false;
        
        for (int i = 0; i < s.length(); i++){
            count[s.charAt(i) - 'a']++;
            count[t.charAt(i) - 'a']--;
        }
        return Arrays.stream(count).allMatch(v -> v == 0);
    }
}

code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        dic_s = dict(collections.Counter(s))
        dic_t = dict(collections.Counter(t))
        return dic_s == dic_t