Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
思路:判断是否是相同字母乱序的,只要排个序或者数字母个数就可以了。
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s)==sorted(t)
下面这个速度要快一些 Counter("abcdcba") ----->Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
from collections import Counter
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return Counter(s)==Counter(t)

本文介绍了一种简单有效的方法来判断两个字符串是否为彼此的字谜变位词。通过排序或使用计数器比较两个字符串中字符的出现次数,可以快速确定它们是否由相同的字母组成,只是顺序不同。这种方法适用于仅包含小写字母的字符串。
650

被折叠的 条评论
为什么被折叠?



