【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

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