给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:你可以假设字符串只包含小写字母。
题目分析:
根据题目的意思,字母异位词是指由相同的字母按照不同的顺序组成的单词,根据此含义,那么这两个单词的长度也一定相等,所以我们就可以先将两个单词按照字母的大小进行排序,然后比较两个单词对应位置上的字母是否相等。
代码实现:
from collections import Counter
s1 = 'below'
s2 = 'elbow'
print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')
# or we can also do this using the sorted() method like this.
print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')
print(sorted(s1))
print(sorted(s2))
结果:
anagram
anagram
['b', 'e', 'l', 'o', 'w']
['b', 'e', 'l', 'o', 'w']
一、sort函数如果对python中的列表进行排序,可以使用List类的成员函数sort,该函数会在原空间上进行操作,对列表本身进行修改,不返回副本。
二、sorted函数sorted函数就比sort函数要强大许多了,sort只能对列表进行排序,sorted可以对所有可迭代类型。
上面这个Counter(s1) == Counter(s2),可能有点迷,我们来学习一下Collection包。
Python collections 包的Counter子类
Counter 是 dict 的子类,用来统计数量,下面的例子统计每个单词出现的次数。
from collections import Counter
# 统计单词出现的次数
sentense = 'what is this? this is an apple.'
r = Counter(sentense.split())
print(r)
运行结果:Counter({'is': 2, 'what': 1, 'this?': 1, 'this': 1, 'an': 1, 'apple.': 1})
这样再来看Counter(s1) == Counter(s2),就很好理解了对吗?
参考资料:(链1是java实现比较清晰,链2是python实现比较简洁)
https://blog.csdn.net/os373/article/details/121035063?spm=1000.2115.3001.5927