題目
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
It is an empty string.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
即檢驗輸入字符串中的括號是不是有效的,要求小括號、中括號或大括號必須成對出現,而且順序不能顛倒,括號內爲空。
解法 1
思路
先定義一個字典包含三類成對出現的括號,之後需要用到堆棧。將輸入字符串中出現的括號(小、中、大)並進行入棧操作(append)。當棧內無內容說明輸入中沒有括號沒有成對出現,當棧頂彈出的括號不屬於當前成對括號時說明括號順序錯誤,這兩種情況返回false。遍歷輸入後若棧無內容則返回true否則爲false。
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
# 字典
pairs = {'(':')', '[':']', '{':'}'}
for char in s:
if char in pairs:
stack.append(pairs[char])
else:
if len(stack) == 0 or stack.pop() != char:
return False
return len(stack) == 0
解法 2
思路
直接判斷輸入字符串中有沒有成對出現的括號(小、中、大),有的話將成對括號替換掉,最後判斷字符串s是不是空,空則說明輸入爲空或輸入字符串包含成對括號,返回true;不是空則說明輸入字符串包含無效的括號,返回false。
下面兩段代碼都是這個思路。
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
while "()" in s or "{}" in s or "[]" in s:
s = s.replace("()", "").replace("[]", "").replace("{}", "")
return len(s) == 0
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
temp = len(s)
while(temp != 0 and temp%2 == 0):
s = s.replace("()", "").replace("[]", "").replace("{}", "")
if temp > len(s):
temp = len(s)
else:
temp = 0
return len(s) == 0