[LeetCode] Valid Parentheses

 

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

判断字符串中括号的有效性。

这道题使用stack来存储括号,遍历字符串中的括号。

如果遇到右括号

  这时如果stack为空,则立即返回false。

  如果这时stack中右匹配的左括号,将stack中左括号弹出stack。

  如果这时stack中没有匹配的左括号,返回false。

如果遇到左括号

  将其压入stack中。

最后判断

  如果stack中存在元素,则表示还有未匹配的左括号,返回false

  如果stack不存在元素,则表示所有括号都已匹配成功,返回true

class Solution {
public:
    bool isValid(string s) {
        stack<char> stk;
        for (int i = 0; i != s.size(); i++) {
            if (s[i] == ')' || s[i] == '}' || s[i] == ']') {
                if (stk.empty())
                    return false;
                else if ((s[i] == ')' && stk.top() == '(') || (s[i] == '}' && stk.top() == '{') || (s[i] == ']' && stk.top() == '['))
                    stk.pop();
                else
                    return false;
            }
            else
                stk.push(s[i]);
        }
        if (stk.empty())
            return true;
        else
            return false;
    }
};
// 3 ms
原文地址:https://www.cnblogs.com/immjc/p/7660254.html