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(int i=0;i<s.length();i++){
            if(s[i] == ']' || s[i] == '}' || s[i] == ')'){
                if(st.empty()){
                    return false;
                }else{
                    char c = st.top();
                    st.pop();
                    if((s[i] == ']' && c != '[')||(s[i] == '}' && c != '{') || (s[i] == ')' && c != '('))
                        return false;
                }
           
            }
        else
            st.push(s[i]);
        } 
        return st.empty();
    }
};


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