【LeetCode算法练习(C++)】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.

链接:Valid Parentheses
解法:遍历字符串,左括号入栈,右括号检查栈顶元素,若不对应立即返回失败。时间O(n)

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

Runtime: 3 ms

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章