LeetCode 20 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.

题目大意:给出一个包含三种括号的序列,判断括号是否匹配。

解题思路:用一个栈保存未匹配的左括号,然后遍历字符串,判断当前字符是左括号还是右括号。如果当前字符是左括号,那么将其入栈;如果当前字符是右括号且栈非空,那么判断是否与栈顶的左括号相匹配,如果匹配则弹出栈顶元素,不匹配则返回false。最后判断栈是否为空。

代码如下:

class Solution {
public:
    bool isValid(string s) {
        stack stk;
        int len = s.length();
        for(int i = 0;i < len;i++){
            if(s[i] == '{' || s[i] == '[' || s[i] == '(') {
                stk.push(s[i]);
            } else if(stk.size() && isPair(stk.top(), s[i])){
                stk.pop();
            } else {
                return false;
            }
        }
        return stk.empty();
        
    }
private:
    bool isPair(char x, char y) {
        if( (x == '{' && y == '}') ||
            (x == '[' && y == ']') ||
            (x == '(' && y == ')') ){
            return true;
        }
        else return false;
    }
};

你可能感兴趣的:(字符串)