LeetCode 20 题 判断括号使用是否正确

来源:互联网 发布:一发炮弹多少钱知乎 编辑:程序博客网 时间:2024/05/15 02:06

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.

Subscribe to see which companies asked this question

比直接判断四则运算要简单的多,可以利用栈来进行处理。

(1)遇到左括号就直接压入栈

(2)遇到右括号就弹出,如果弹出的符号和当前不匹配或者栈已经为空,则错误。

(3)如果已经遍历完以后,栈还不为空,则错误

class Solution {
public:
    bool isValid(string s) {
        stack<char> tempStack;
        char tempChar;
        for(int i = 0; i < s.size(); ++i) {
            tempChar = s[i];
            switch(tempChar) {
                case '[':case '(':case '{':
                    tempStack.push(tempChar);
                    break;
                case ')':{
                    if(!tempStack.empty() && tempStack.top() == '('){
                        tempStack.pop();
                    }
                    else
                        return false;
                }
                    break;
                case '}':{
                    if(!tempStack.empty() && tempStack.top() == '{'){
                        tempStack.pop();
                    }
                    else
                        return false;
                }
                    break;
                case ']':{
                    if(!tempStack.empty() && tempStack.top() == '['){
                        tempStack.pop();
                    }
                    else
                        return false;
                }
                    break;
                default:
                    break;
            }
        }
        if(tempStack.empty())
            return true;
        else
            return false;
    }
};

0 0