目录
题目
-
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
法一、字典
- 思路:用两个字典统计两个字符串中每个字符出现的次数,最后进行比较,如果每个字符出现次数同,则返回True
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dit1={}
dit2={}
for i ,char in enumerate (s):
if char not in dit1:
dit1[char] = 1
else:
dit1[char] += 1
for i, char in enumerate (t):
if char not in dit2:
dit2[char] = 1
else:
dit2[char] += 1
for j in range (len(s)):
if dit1 == dit2:
return True
return False
- 简洁的代码
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dit1 = {}
dit2 = {}
for char in s:
if char not in dit1:
dit1[char] = 1
else:
dit1[char] += 1
for char in t:
if char not in dit2:
dit2[char] = 1
else:
dit2[char] += 1
return dit1 == dit2
标签:dit1,dit2,异位,字母,else,char,str,242
From: https://www.cnblogs.com/lushuang55/p/17782425.html