[Leetcode] 242. Valid Anagram

更新於 發佈於 閱讀時間約 3 分鐘

題目: 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



留言
avatar-img
留言分享你的想法!
avatar-img
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
Youna's Devlog的其他內容
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
看更多
你可能也想看
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
題目敘述 題目會給定一個整數陣列arr,要求我們判斷是否每個元素的出現次數都不同? 題目的原文敘述 測試範例 Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurre
Thumbnail
題目敘述 題目會給定一個整數陣列arr,要求我們判斷是否每個元素的出現次數都不同? 題目的原文敘述 測試範例 Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurre
Thumbnail
題目敘述 題目會給我們兩個字串作為輸入,分別是字串s和字串t,問我最少要做幾次字元轉換,讓字串t和字串s成為Anagram"同字母異序詞"? 註: 例如 god 和 dog 就是 Anagram 同字母異序詞,也是就說,組成字母相同,但是順序可以重新排列。 題目的原文敘述 測試範例 Ex
Thumbnail
題目敘述 題目會給我們兩個字串作為輸入,分別是字串s和字串t,問我最少要做幾次字元轉換,讓字串t和字串s成為Anagram"同字母異序詞"? 註: 例如 god 和 dog 就是 Anagram 同字母異序詞,也是就說,組成字母相同,但是順序可以重新排列。 題目的原文敘述 測試範例 Ex
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News