[leetcode] 20. Valid Parentheses

題目鏈接:https://leetcode.com/problems/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.

思路

利用一個棧來保存需要匹配的左括號,碰到右括號則判斷棧頂需要匹配的是不是此類型的括號,最後棧爲空即左括號完全被匹配則爲合法字符串。

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(auto val:s){
            if(val == '(' || val == '{' || val == '[')
                st.push(val);
            if(val == ')'){
                if(st.empty() ||st.top() != '(') 
                    return false;
                else st.pop();
            }
            if(val == '}'){
                if(st.empty() || st.top() != '{')
                    return false;
                else st.pop();
            }
            if(val == ']'){
                if(st.empty() || st.top() != '[')
                    return false;
                else st.pop();
            }
        }
        return st.empty();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章