有效的括号

题目描述

来源于 https://leetcode-cn.com/

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解法:

使用栈很容易解决,需要注意的是在 pop 的时候需要检查栈是否为空。

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> mapping{
            {')', '('},
            {']', '['},
            {'}', '{'}
        };
        stack<char> stk;
        for(auto c: s){
            if(c == '(' || c == '[' || c == '{'){
                stk.push(c);
            }else{
                if(stk.empty() || stk.top() != mapping[c]){
                    return false;
                }else{
                    stk.pop();
                }
            }
        }
        return stk.empty();
    }
};