20. Valid parentheses

Idea :
The principle of checking parenthesis pairing is as follows: During the process of scanning the text, the closing parenthesis encountered should be paired with the opening parenthesis that has been encountered recently and has not yet been matched . If the recently unmatched opening bracket does not match the current closing bracket, or if no such opening bracket is found, the match fails, indicating that the brackets in the text do not match.
Since the occurrences of parentheses may be nested, pair-wise matching is required: the current closing parenthesis should match the nearest preceding open parenthesis that has not yet been matched, and the next parenthesis should match the next nearest preceding parenthesis. This shows that the use principle of the opening brackets that need to be stored is that the last depositor uses it first, which is in line with the LIFO principle.
Furthermore, if a symbol has been matched, the parentheses should be removed in preparation for subsequent matching. Obviously, in the process of scanning, the opening brackets encountered and saved will be paired and deleted first, which is LIFO in the order of appearance. These cases show that using the stack to save the opening brackets encountered can support the matching work.
The specific python code is as follows:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 == 1:
            return False
        Stack = []
        char_dict = {
    
    
            "]":"[",
            ")":"(",
            "}":"{"
        }
        # 扫描符号
        for char in s:
            # 判断闭括号
            if char in char_dict:
                # not Stack是指不为空,则说明左右括号不一致
                # Stack.pop()如果不匹配则返回False,如果匹配Stack也执行了出栈操作(重点)
                if not Stack or char_dict[char] != Stack.pop():
                    return False
            # 保存开括号
            else:
                Stack.append(char)
        return not Stack

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339346&siteId=291194637