Leetcode: Valid Parentheses 有效的括号匹配

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<char> stk;
        stk.push('#');
        for (int i = 0; i < s.size(); ++i) {
            if (isLeft(s.at(i))) {
                stk.push(s.at(i));
            } else {
                if (isPair(stk.top(), s.at(i))) {
                    stk.pop();
                } else {
                    return false;
                }
            }
        }
        return stk.top() == '#';
    }
    
    bool isLeft(char c) {
        if (c == '(' || c == '{' || c == '[') {
            return true;
        } else {
            return false;
        }
    }
    
    bool isPair(char a, char b) {
         return (a == '(' && b == ')') || (a == '{' && b == '}') || (a == '[' && b == ']');
    }
};

 

你可能感兴趣的:(LeetCode)