括号匹配 leetcode 20

题目

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: "()"
输出: true

示例 2:
输入: "(]"
输出: false

思路

python代码

自己的代码,又丑又长

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for i in s:
            if i == '(' or i == '[' or i == '{':
                stack.append(i)
            else:
                if len(stack) == 0: return False
                elem = stack.pop()
                if i == ')' :
                    if elem != '(':
                        return False
                    else:
                        continue
                elif i == ']':
                    if elem != '[':
                        return False
                    else:
                        continue
                elif i == '}':
                    if elem != '{':
                        return False
                    else:
                        continue
        
        if len(stack) == 0:
            return True
        else:
            return False
                    

官方写法,代码简洁精炼

class Solution:
    def isValid(self, s: str) -> bool:
        stack = list()
        pairs={']':'[', '}':'{', ')':'('}

        for i in s:
            if i in pairs:
                if not stack or stack[-1] != pairs[i]:
                    return False
                stack.pop()
            else:
                stack.append(i)
        
        return not stack

c++代码

class Solution {
public:
    bool isValid(string s) {
        int n = s.size();
        if (n % 2 == 1) {
            return false;
        }

        unordered_map pairs = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };
        stack stk;
        for (char ch: s) {
            if (pairs.count(ch)) {
                if (stk.empty() || stk.top() != pairs[ch]) {
                    return false;
                }
                stk.pop();
            }
            else {
                stk.push(ch);
            }
        }
        return stk.empty();
    }
};

你可能感兴趣的:(括号匹配 leetcode 20)