赞
踩
如果两个字符串的长度就不一致,那么直接return False。
如果一致的话,遍历字符串s,记录字符串s中每个字母出现的次数到字典d中。然后遍历字符串t,减少字典d中对应字母的出现次数,如果对应字母出现次数少于0了,则return False。如果遍历了一遍字符串t,依然没有return False,则证明两个字符串互为字母异位词,那么就return True。
class Solution: def isAnagram(self, s: str, t: str) -> bool: d = {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0, 'v':0, 'w':0, 'x':0, 'y':0, 'z':0 } # 两个字符串的长度不一致时,肯定不为异位词 if len(s) != len(t): return False else: # 统计字符串s的字符情况 for i in range(len(s)): d[s[i]] += 1 i += 1 # 验证字符串t的情况 for j in range(len(t)): d[t[j]] -= 1 if d[t[j]] < 0: return False break j += 1 return True
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。