0242. Valid Anagram

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

Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

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.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

ac

class Solution {
    public boolean isAnagram(String s, String t) {
        // edge case
        if (s == null || t == null) return false;

        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            map.put(c, map.getOrDefault(c, 0) - 1);
        }

        // check
        for (char k : map.keySet()) {
            if (map.get(k) != 0) return false;
        }
        return true;
    }
}

Last updated