問題描述:
給定兩個字串 s 和 t ,編寫乙個函式來判斷 t 是否是 s 的乙個字母異位詞。
示例 1:
輸入:s = "anagram", t = "nagaram"輸出:true示例 2:
輸入:s = "rat", t = "car"輸出:false說明:
你可以假設字串只包含小寫字母。
高階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?
方法1:每次從s中查詢t首部的乙個字母,更新s和t。(時間複雜度太大)
1class
solution(object):
2def
isanagram(self, s, t):
3"""
4:type s: str
5:type t: str
6:rtype: bool
7"""
8if len(s) !=len(t):
9return
false
10while
s:11 index =s.find(t[0])
12if index >=0:
13 s = s[:index] + s[index+1:]
14 t = t[1:]
15else:16
return
false
17if t ==s:
18return
true
19return false
方法2:官方
1class
solution(object):
2def
isanagram(self, s, t):
3"""
4:type s: str
5:type t: str
6:rtype: bool
7"""
8 s=list(set(s))
9 t=list(set(t))
10if len(s)!=len(t):
11return
false
12for i in
s:13
if i in t and s.count(i)==t.count(i):
14pass
15else:16
return
false
17return true
簡潔一點:
1class
solution:
2def
isanagram(self, s, t):
3"""
4:type s: str
5:type t: str
6:rtype: bool
7"""
8return set(s) == set(t) and all(s.count(i) == t.count(i) for i in set(s))
2018-09-21 15:41:43
Leetcode 242 有效的字母異位
time 20190901 type easy 給定兩個字串 s 和 t 編寫乙個函式來判斷 t 是否是 s 的字母異位詞。示例 1 輸入 s anagram t nagaram 輸出 true 示例 2 輸入 s rat t car 輸出 false 說明 你可以假設字串只包含小寫字母。高階 如果...
LeetCode242 有效的異位詞
給定兩個字串 s 和 t 編寫乙個函式來判斷 t 是否是 s 的字母異位詞。示例 1 輸入 s anagram t nagaram 輸出 true示例 2 輸入 s rat t car 輸出 false說明 你可以假設字串只包含小寫字母。高階 如果輸入字串包含 unicode 字元怎麼辦?你能否調整...
LeetCode 242 有效的字母異位
給定兩個字串 s 和 t 編寫乙個函式來判斷 t 是否是 s 的字母異位詞。說明 你可以假設字串只包含小寫字母。高階 如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?思路 兩個字串長度不等,則不滿足。兩個字串相等,則滿足。定義兩個陣列,分別記錄s和t中每個字母出現的次...