leetcode 字谜

本文探讨了一种有效的算法,用于确定两个给定的字符串是否互为字母异位词。通过比较每个字符串中所有小写字母的出现次数,算法能够快速判断两个字符串是否包含相同的字符集,从而实现对字母异位词的验证。
242. Valid Anagram
Easy
66298FavoriteShare

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

 

 

ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_l = len(s)
t_l = len(t)
dic = {}
for i in range(97,123):
dic[chr(i)] = [0,0]
if s_l != t_l:
return False
for i in s:
dic[i][0] += 1
for j in t:
dic[j][1] += 1
for j in t:
if dic[j][0] != dic[j][1]:
return False
return True

 

最优的方法

 

class Solution:
def isAnagram(self, s: str, t: str) -> bool:

'''
s_l = len(s)
t_l = len(t)
dic = {}
for i in range(97,123):
dic[chr(i)] = [0,0]
if s_l != t_l:
return False
for i in s:
dic[i][0] += 1
for j in t:
dic[j][1] += 1
for j in t:
if dic[j][0] != dic[j][1]:
return False'''
for i in string.ascii_lowercase:
if s.count(i) != t.count(i):
return False
return True

return True

转载于:https://www.cnblogs.com/find1/p/10770938.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值