0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Valid Anagramをpythonで解き方を詳しく説明してみる

Posted at

Valid Anagram

上記の問題になります。

簡潔に言えばsを並び替えてtはできるのか?という問題です。

解説

最初に考えることはs,tは同じ長さかということです。
文字列sをどのように並び替えたらtができるのかを考える前に長さが異なればsからtを作ることが不可能です。
そのため先に

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

そして、ここから考えていきます。
文字列sはアルファベットしかありません。ここから24種類のアルファベットがsの中にいくつ出てきているかをカウントする、同時にtをカウントする。その種類と数が一致するとTrueを返すように作ればいいじゃないのか?と考えることができます。

ここからハッシュマップを作っていきます。

ハッシュマップはここから詳しくわかります。

無題のプレゼンテーション.png
このように出てきたアルファベットをカウントしていきます。
このようにしてハッシュマップを作っていきます。
以下は実装です。

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        dict_s, dict_t = {},{}
        for i in range(len(dict_s)):
            dict_s[s[i]] = 1 + dict_s.get(s[i],0)
            dict_t[t[i]] = 1 + dict_t.get(t[i],0)
        return dict_s == dict_t

ポイント

dictのget関数

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?