242. Valid Anagram

Question: Valid Anagram

Solution

重複排列之後,兩個 string 可以長一樣

代表兩個 string 的 element 要一樣之外,個數也要一樣

  • key:string 的字元包含哪些
  • value:每個字元的個數

所以我們選用 dictionary 這個 data structure

from collections import defaultdict

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_hash = defaultdict(int)
t_hash = defaultdict(int)
for i in range(len(s)):
s_hash[s[i]] += 1
t_hash[t[i]] += 1
if s_hash == t_hash:
return True
return False

Video Solution


Comments

Popular Posts