Valid Anagram

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

Given two stringssandt, write a function to determine iftis an anagram ofs.

For example, s= "anagram",t= "nagaram", return true. s= "rat",t= "car", return false.

Note: You may assume the string contains only lowercase alphabets.

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

Thoughts

想法很直观。

Code

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() == 0 && t.length() == 0) {
            return true;
        } else if (s.length() == 0) {
            return false;
        }

        Map<Character, Integer> freq = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (!freq.containsKey(s.charAt(i))) {
                freq.put(s.charAt(i), 1);
            } else {
                freq.put(s.charAt(i), freq.get(s.charAt(i)) + 1);
            }

        }

        for (int i = 0; i < t.length(); i++) {
            if (!freq.containsKey(t.charAt(i)) || freq.get(t.charAt(i)) == 0) {
                return false;
            }
            freq.put(t.charAt(i), freq.get(t.charAt(i)) - 1);
        }

        for (Character c : freq.keySet()) {
            if (freq.get(c) != 0) {
                return false;
            }
        }
        return true;
    }
}

Analysis

Errors:

  1. 不能用XOR, 因为可以"aabb"和"ccdd"同样返回0.

  2. s中元素可能比t的多

时间复杂度O(N), 空间O(1).

Last updated