240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 18 | Leetcode 20. Valid Parentheses

题解

Easy

Stack

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        int i = 0;
        while(i < s.size()) {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
                st.push(s[i]);
            } else {
                if(st.empty()) return false;
                char c = st.top();
                st.pop();
                if(s[i] == ')') {
                    if(c != '(') return false;
                } else if (s[i] == ']') {
                    if(c != '[') return false;
                } else if (s[i] == '}') {
                    if(c != '{') return false;
                }
            }
            i++;
        }
        
        return st.size() == 0;
    }
};
posted @ 2020-10-03 06:28  CasperWin  阅读(102)  评论(0编辑  收藏  举报