题目一:
"""
查找排序相关面试题
>1.给两个字符串s和t,判断t是否为s的重新排列后组成的单词
>s = "anagram", t = "nagaram", return true.
> s = "rat", t = "car", return false.
"""
class Solution:
def isAnagram(self,s,t):
"""
:type s:str
:type t:str
:rtype:boot
"""
ss=list(s)
tt=list(t)
ss.sort()
tt.sort()
return ss==tt
s='anagram'
t='nagaram'
duixiang1=Solution()
res=duixiang1.isAnagram(s,t)
print(res)
时间复杂度:NlogN
一行代码解决:
class Solution:
def isAnagram(self,s,t):
"""
:type s:str
:type t:str
:rtype:boot
"""
# ss=list(s)
# tt=list(t)
# ss.sort()
# tt.sort()
# return ss==tt
return sorted(list(s))==sorted(t)
s='anagram'
t='nagaram'
duixiang1=Solution()
res=duixiang1.isAnagram(s,t)
print(res)
"""
查找排序相关面试题
>1.给两个字符串s和t,判断t是否为s的重新排列后组成的单词
>s = "anagram", t = "nagaram", return true.
> s = "rat", t = "car", return false.
"""
class Solution:
def isAnagram(self,s,t):
"""
:type s:str
:type t:str
:rtype:boot
"""
# 第1种方法
# ss=list(s)
# tt=list(t)
# ss.sort()
# tt.sort()
# return ss==tt
#第二种方法
# return sorted(list(s))==sorted(t)
# 第3种方法
dict1={}#{'a':1,'b':2)
dict2={}
for ch in s:
dict1[ch]=dict1.get(ch,0)+1
for ch in t:
dict2[ch] = dict2.get(ch, 0) + 1
return dict1==dict2
s='anagram'
t='nagaram'
duixiang1=Solution()
res=duixiang1.isAnagram(s,t)
print(res)