每日一題: 有效括號

freephp發表於2024-04-07

面對這個括號匹配的問題,我開始也有點迷茫,隱約覺得可以用棧(Stack)來解決。一起先來看看原題吧:


Given a string s 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.
Every close bracket has a corresponding open bracket of the same type.
 

Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
 

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

當成一個數學問題來看,先找出規則規律,如果先來一個關閉型別的括號(如),], }),那麼直接就算false了,如果開和閉合沒有成對出現,也會是false。我們可以拿一個Stack來儲存open bracket,當迴圈的當前的字元是open bracket就push到stack。
噹噹前的字元是closed bracket則彈出頂部Stack的元素,看是否是對應的open bracket,如果是就繼續迴圈,如果不是則返回false。
還要考慮一些邊界情況,如果在彈出元素的時候剛好stack為空了,也說明沒有配套的open bracket了,也應該返回false。

用Python實現的程式碼如下,非常清晰:


class Solution:
    def isValid(self, s: str) -> bool:
        bracketMap = {
            "(": ")",
            "{": "}",
            "[": "]"
        }

        stack = []

        for char in s:
            if char in bracketMap:
                # push the open bracket into the stack
                stack.append(char)
            else:
                # If the stack is empty or do not have the matching open bracket, it means the closed bracket does not have the related open bracket
                if len(stack) == 0 or bracketMap[stack.pop()] != char:
                    return False

        return len(stack) == 0
        

相關文章