LoginSignup
0
1

More than 3 years have passed since last update.

stackの問題:「20. Valid Parentheses」を解いてみる

Posted at

はじめに

stackの問題を解いたので,メモしました.

「20. Valid Parentheses」を解いてみる

問題へのリンク:
https://leetcode.com/problems/valid-parentheses/

解答:


class Solution:
    def isValid(self, s: str) -> bool:
      if len(s)%2 != 0:
        return False

      dic = {'(':')','{':'}','[':']'}
      stack = list()

      for i, c in enumerate(s):
        if s[i] in dic: # verify only left-bracket
          stack.append(s[i]) # add only left-bracket
        else:
          if len(stack) != 0 and dic[stack[-1]] == s[i]:
            stack.pop() # remove a last element
          else:
            return False

      if len(stack) == 0:
        return True

この処理の流れについて説明します.

まず,左・右かっこをそれぞれペアとした辞書,stackというリストを作成します.

そして,入力の文字列を前から順に見ていき,左かっこの場合はstackに追加.(stackに追加されるのは左かっこのみ)
右かっこの場合はstackの最後の要素がペアとなる左かっこであればその左かっこをstackから除去.(そうでない場合はFalseを返し終了)

最終的に,stackの中身が空となればTrueを返します.

0
1
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
1