一.题目
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
二.思路和代码
1.为每个字符串建立hash table,然后循环某字符串,如果某一个元素同时也在另一个字符串里,那么同时删除两个哈希表的这一项。最后判断两个hash table 是否都为空。运行时间有点长,但可以过。
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
else:
hash_table_s = {}
hash_table_t = {}
for i in s:
if ord(i) in hash_table_s:
hash_table_s[ord(i)] += 1
else:
hash_table_s[ord(i)] = 1
for j in t:
if ord(j) in hash_table_t:
hash_table_t[ord(j)] += 1
else:
hash_table_t[ord(j)] = 1
for c in s:
if ord(c) in hash_table_t:
if hash_table_s[ord(c)] == 1:
hash_table_s.pop(ord(c))
else:
hash_table_s[ord(c)] -= 1
if hash_table_t[ord(c)] == 1:
hash_table_t.pop(ord(c))
else:
hash_table_t[ord(c)] -= 1
if hash_table_s == {} and hash_table_t == {}:
return True
else:
return False
2. 使用题目内部逻辑构造判断语句:对于字母异位词我们可以看出有两个条件可以限定,第一是两串字符串出现的字母相同,第二是这些字母出现的次数相同。
对于第一个限定条件可以用set()来解决;第二个限定条件可以使用字符串的count() 方法。
return (set(s) == set(t) and all(s.count(i) == t.count(i) for i in set(s)))
all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为True,如果是返回 True,否则返回 False (返回的是一个bool值)。与之对应的的还有any(): 只要可迭代参数iterable有一个是True那么就返回True。
元素除了是 0、空、FALSE 外都算True。