1. 程式人生 > >LeetCode--242--有效的字母異位詞

LeetCode--242--有效的字母異位詞

時間復雜度 sel spa 說明 復雜度 color lee and nic

問題描述:

給定兩個字符串 st ,編寫一個函數來判斷 t 是否是 s 的一個字母異位詞。

示例 1:

輸入: s = "anagram", t = "nagaram"
輸出: true

示例 2:

輸入: s = "rat", t = "car"
輸出: false

說明:
你可以假設字符串只包含小寫字母。

進階:
如果輸入字符串包含 unicode 字符怎麽辦?你能否調整你的解法來應對這種情況?

方法1:每次從s中查找t首部的一個字母,更新s和t。(時間復雜度太大)

 1 class Solution(object):
 2     def isAnagram(self, s, t):
3 """ 4 :type s: str 5 :type t: str 6 :rtype: bool 7 """ 8 if len(s) != len(t): 9 return False 10 while s: 11 index = s.find(t[0]) 12 if index >= 0: 13 s = s[:index] + s[index+1:] 14 t = t[1:]
15 else: 16 return False 17 if t == s: 18 return True 19 return False

方法2:官方

 1 class Solution(object):
 2     def 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)) 10 if len(S)!=len(T): 11 return False 12 for i in S: 13 if i in T and s.count(i)==t.count(i): 14 pass 15 else: 16 return False 17 return True

簡潔一點:

1 class Solution:
2     def isAnagram(self, s, t):
3         """
4         :type s: str
5         :type t: str
6         :rtype: bool
7         """ 
8         return 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--有效的字母異位詞