「(」、「)」、「{」、「}」、「[」、「]」のみで構成される文字列が指定された場合、その文字列が有効かどうかを確認します。
有効な文字列は次の条件を満たす必要があります。
- 開始ブラケットは、同じタイプの終了ブラケットで閉じる必要があります。
- 開き括弧は正しい順序で閉じる必要があります。
空の文字列は有効な文字列とみなされます。
アルゴリズムのアイデア: スタックPython コードの使用
class Solution:
def isValid(self, s: str) -> bool:
t = []
for i in s:
if i == "(" or i == "{" or i == "[":
t.append(i)
elif i == ")":
if len(t) == 0 or t.pop() != "(":
return False
elif i == "}":
if len(t) == 0 or t.pop() != "{":
return False
elif i == "]":
if len(t) == 0 or t.pop() != "[":
return False
if len(t) == 0:
return True
else:
return False