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?

1日1回感謝のleetcode #6 [20. Valid Parentheses]

0
Posted at

AIが何もかもやってくれる時代になりつつある中で私は人間臭いプロダクトを作っていきたいと思っています。

※1日1leetcodeをやる理由は第1回を見てください
1日1回感謝のleetcode #1 [141. Linked List Cycle]

20. Valid Parentheses

今日からstackの話になるみたいですね。
問題は引数で与えられた括弧の文字列が括弧として機能しているかどうかを見てboolを返す実装を作るようです。
これ、しばらく考えてたんですけど普通にめっちゃ難しくないですか。ほんまにEasyか?
ってことであまりに強引な方法しか浮かばないためgeminiちゃんにヒントをもらいました。

gemini「文字列をstackに入れてくイメージで考えてみ」

なるほどね。文字列から一文字ずつ取って始まり括弧ならstackにpushして閉じ括弧ならpopして括弧が成り立つかどうか見ればいいのか。
いやーーーーーー、これはめちゃくちゃ良問だ、、。
stackってデータ構造と括弧のルールを理解した途端にどうすればいいのかすぐ浮かんできた。
これを一発で思い浮かべるようにならないといけないね。
というわけで実装してみました。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for chara in s:
            if chara in "({[":
                stack.append(chara)
            elif chara in ")}]":
                if stack:
                    if stack[-1] == '(' and chara == ')':
                        stack.pop()
                    elif stack[-1] == '{' and chara == '}':
                        stack.pop()
                    elif stack[-1] == '[' and chara == ']':
                        stack.pop()
                    else:
                        return False
                else:
                    return False
        if stack:
            return False
        return True

うわっ…私のネスト、深すぎ…?
提出してacceptedは貰えたけど怒涛の条件式祭りでブーメランのアスキーアートみたいになっとる🪃

リファクタリングしてみた。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for chara in s:
            if chara in "({[":
                stack.append(chara)
            else:
                if stack and stack[-1] == '(' and chara == ')':
                    stack.pop()
                elif stack and stack[-1] == '{' and chara == '}':
                    stack.pop()
                elif stack and stack[-1] == '[' and chara == ']':
                    stack.pop()
                else:
                    return False
        return not stack

さっきよりはましになったが、これ以上はどう削るか浮かばないためgeminiちゃんに相談。

gemini「アルゴリズムとしては満点じゃ。だけどif,elifのところは辞書でやればもっと上手くかけるぞ。」

うーん?辞書でやる?
ちょっと考えてみようか。
辞書で管理するなら閉じ括弧をkeyにして.get()した値がpopした値を一致するかを見ればいいからこんな感じかな。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        dic = {')':'(', '}':'{', ']':'['}
        for chara in s:
            if chara in dic.values():
                stack.append(chara)
            else:
                if stack and dic.get(chara) == stack[-1]:
                    stack.pop()
                else:
                    return False
        return not stack

かなり可読性も高くまとまったね。
空間計算量もO(n)らしい(まだちゃんと理解できてない)し時間計算量もO(n)なのでこれで大丈夫かな。

いやーこれはいい問題だった。
ではまた明日。

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?