# 242-Valid Anagram ###### tags: `Easy`、`String` ## Question ![](https://i.imgur.com/IJQAj7i.png) https://leetcode.com/problems/valid-anagram/ ## Solution - Anagram即字母相同可以拼出不同單字,所以先檢查各自字母數目相同,再檢查是否字母相同 ### C++ with hash table ```cpp= class Solution { public: bool isAnagram(string s, string t) { if(s.size() != t.size()) { return false; } unordered_map<char, int> umap; unordered_map<char, int> umap2; for(int i = 0; i<s.size();i++) { umap[s[i]]++; } for(int i = 0; i<t.size();i++) { umap2[t[i]]++; } for(int i = 0; i<s.size();i++) { if(umap2.count(s[i])) { if(umap[s[i]] != umap2[s[i]]) { return false; } } else { return false; } } return true; } }; ``` ### Python solution ```python= class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s)!=len(t): return False chars = set(s) for i in chars: if i not in t or s.count(i)!=t.count(i) : return False return True ```