0
0

Balanced Parentheses(括弧の対応検査)

Posted at

問題

3種類の括弧 ( ),{ },[ ]からなる文字列について,以下の条件を満たすか否かを判定したい.

  • 同種の括弧同士が,必ず閉じている

  • 具体例
    ⭕️:()  ,([ ]) , { } [ ], ([ ] {[ ]} )
    ❌:( ,   [[[,   {),    ([{ ])

発想

  • かっこのペアを打ち消しあって,全てなくなったらOK
  • 左から順にスタックにpush➡️打ち消しあったらpopを繰り返し,スタックが空になればTrueを返す

コード例(Python)

from collections import deque

def judge_balance(S):

    stack=deque()
    
    for c in S:

        # スタックが空でなければ,整合性を検査
        if stack:                
            if stack[-1]=='(' and c==')' :
                stack.pop()
            elif stack[-1]=='[' and c==']' :
                stack.pop()
            elif stack[-1]=='{' and c=='}' :
                stack.pop()
            else:
                stack.append(c)
        # スタックが空ならば要素を追加
        else:
            stack.append(c)
        
        

    # 最終的にスタックが空でなければ,正しくない括弧列,空なら正しい括弧列
    if stack:
        return False
    else:
        return True


S=input()
if judge_balance(S):
    print("Yes")
else:
    print("No")
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