2023-11-28|閱讀時間 ‧ 約 3 分鐘

[Leetcode] 242. Valid Anagram

題目: 242. Valid Anagram

  • 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


  1. sorted()函數

將2個字串用sorted()進行排序,再比對是否一樣

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)


  1. Counter類別

s ="anagram" t ="nagaram"

Counter(s) => Counter({'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1})

Counter(t) => Counter({'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1})

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)


  1. Hashmap


class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

dicts, dictt = {},{}

for i in range(len(s)):
dicts[s[i]] = dicts.get(s[i],0) + 1
dictt[t[i]] = dictt.get(t[i],0) + 1

return dicts == dictt



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.