天天看点

【Leetcode每日一题】242. 有效的字母异位词(水题)

Leetcode每日一题

题目链接: 242. 有效的字母异位词

难度: 简单

解题思路: 判断两个单词是否是字母异位词(不看位置同构的词)。记录两个单词的字母出现次数是否是相等的。

题解:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        visit = {}
        for example in s:
            visit[example] = visit.get(example, 0) + 1
        for example in t:
            if visit.get(example) != 0 and visit.get(example):
                visit[example] -= 1
        
        flag = True
        for vexample in visit:
            if visit[vexample] > 0:
                flag = False
                break
        
        return flag