---
# System prepended metadata

title: 242 - Valid Anagram
tags: [LeetCode]

---


# 242 - Valid Anagram
![](https://i.imgur.com/QlvCHLM.jpg)

Problem
---


Solution
---


用Hashmap 把字串裡面的字母以及出現頻率存下來，原本預計會用兩個Hashmap存下來後再比對，但看了解答發現只需要用一個Hashmap存，然後再另一個單字的loop去對照map出現的字母，把出現的頻率減掉，如果沒有這個字母，或是減的當下已經是0，就直接回傳false

use a HashMap to store the frequency of each character in the first string s. We use the toCharArray method of the String class to convert the strings into char arrays so that we can iterate through them using a for loop. We also use the containsKey method and the getOrDefault method of the Map interface to check if a character is present in the HashMap and to increment its frequency. Finally, we use the put method to update the frequency of each character in the HashMap.

---

```
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }

    Map<Character, Integer> freq = new HashMap<>();


    for (char c : s.toCharArray()) {
        freq.put(c, freq.getOrDefault(c, 0) + 1);
    }

    for (char c : t.toCharArray()) {
        if (!freq.containsKey(c) || freq.get(c) == 0) {
            return false;
        }
        freq.put(c, freq.get(c) - 1);
    }

    return true;
}
```

###### tags: `LeetCode`
