題目:給定兩個字元串s和t,寫出一個程式判斷s是否為t的回文字元串。
例:s=”anagram”, t=”nagaram” 傳回true
s=”car”, t=”ant” 傳回false
解題思路1:使用sorted函數,将字元串排序,如:
sorted(s)=[‘a’,’a’,’a’,’g’,’m’,’n’,’r’],
sorted(t)=[‘a’,’a’,’a’,’g’,’m’,’n’,’r’]
代碼1:
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return(sorted(s)==sorted(t))
解題思路2:使用2個字典,分别将2個字元串中每個字母作為key,每個字母出現次數作為value,使用如下語句計數:
dic1[item] = dic1.get(item, 0) + 1
代碼2:
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic1,dic2={},{}
for item in s:
dic1[item] = dic1.get(item,0)+1
for item in t:
dic2[item] dic.get(item,0)+1
return (dic1==dic2)
解題思路3:使用1個字典,将字元串中每個字母作為key,每個字母出現次數作為value ,s中出現1個字元,字典key值對應的value加1,t中出現相同字元,字典key值對應的value減1.
代碼3:
from collections import defaultdict #标準字典庫
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t): #首先判斷長度是否相同
return False
else:
dic = defaultdict(int)
for i in range(len(t)):
dic[s[i]] +=1
"""
s[i]為字元串中的字母,dic[s[i]]為字母所對應的key值
"""
dic[t[i]] -=1
for key,value in dic.iteritems():
if value !=0:
return False
return True