###### tags: `Leetcode` `easy` `hash` `string` `python` `c++` # 242. 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. 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 ``` ## 解題想法: * 此題為判斷t是否為s的重組字 * 使用hash table * 紀錄s字串所有字出現次數 * 再逐一比較t字串即可 ## Python: ``` python= from collections import defaultdict class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s)!=len(t): return False dic=defaultdict(int) for char in s: dic[char]+=1 for char in t: dic[char]-=1 if dic[char]<0: return False return True if __name__ == '__main__': result = Solution() s = "anagram" t = "nagaram" ans = result.isAnagram(s,t) print(ans) ``` ## C++: ``` cpp= #include<bits/stdc++.h> using namespace std; class Solution { public: bool isAnagram(string s, string t) { unordered_map<char, int> dic; if (s.size()!=t.size()) return false; for (char val: s) dic[val]+=1; for (char val: t){ dic[val]-=1; if (dic[val]<0) return false; } return true; } }; ```