iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

試煉之地 Leetcode 的挑戰系列 第 11

Leetcode 挑戰 Day 11 [242. Valid Anagram]

242. Valid Anagram


今天我們一起挑戰leetcode第242題Valid Anagram!

題目


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:
Input: s = "anagram", t = "nagaram"
Output: true

Example 2:
Input: s = "rat", t = "car"
Output: false

這題的題目描述雖然很短,但乍看之下又不知道他到底要我們做什麼,他要我們確認t是s的anagram,但anagram的意思是什麼?經過查詢之後才知道,原來anagram的意思類似是字的重組與排序,也就是說這個題目要問我們s與t在經過字元任意排序後,是否可以長得一模一樣。

Sorted


這類型的問題其中一個解決方法就是使用排序,只要將兩個字串都按照同樣的規則排序,如果他們在經過排序後長得一樣,就符合了anagram的定義,因此我們可以使用程式內建的排序函式、也可以自刻一個排序演算法,來達到題目的要求。

以下是python3的程式碼

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if sorted(s) == sorted(t):
            return True
        return False
        
        #  也可以只寫一行 return sorted(s) == sorted(t)

以下解法是另一組思路,用HashMap也能達到檢視兩組字串是否再重新排列以後成為相同的字串。

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dict_ = {}
        for i in s:
            if i not in dict_:
                dict_[i] = 1
            else:
                dict_[i] += 1
        for i in t:
            if i not in dict_:
                return False
            elif dict_[i] == 1:
                del dict_[i]
            else:
                dict_[i] -= 1
        return not dict_


上一篇
Leetcode 挑戰 Day 10 [171. Excel Sheet Column Number]
下一篇
Leetcode 挑戰 Day 12 [ 26. Remove Duplicates from Sorted Array]
系列文
試煉之地 Leetcode 的挑戰19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言