6/1 每日一題(異位字串)
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104sandtconsist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
#法一
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_set=set() #計算元素
for i in s:
s_set.add(i)
for i in s_set:
if s.count(i) != t.count(i):
return False
return True
#法二
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# if len(s) != len(t):
# return False
# s_set=set() #計算元素
# for i in s:
# s_set.add(i)
# for i in s_set:
# if s.count(i) != t.count(i):
# return False
# return True
return Counter(s) == Counter(t)
#法三class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# if len(s) != len(t):
# return False
# s_set=set() #計算元素
# for i in s:
# s_set.add(i)
# for i in s_set:
# if s.count(i) != t.count(i):
# return False
# return True
# return Counter(s) == Counter(t)
a=sorted(s)
b=sorted(t)
return a==b

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁