LeetCode #20 Valid Parentheses

Description

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.


Analysis

题目难度为:Easy
括号匹配考查的是栈的出入栈问题——如果是左括号则入栈,如果是右括号,栈顶是相匹配的左括号则左括号出栈。当输入右括号,栈为空或者栈顶括号不匹配,则匹配出错。


Code(c++)

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

你可能感兴趣的:(leetcode)