美文网首页Leetcode
Leetcode 20. Valid Parentheses

Leetcode 20. Valid Parentheses

作者: SnailTyan | 来源:发表于2018-09-25 18:36 被阅读36次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Valid Parentheses

2. Solution

  • Version 1
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(char ch : s) {
            if(st.empty()) {
                st.push(ch);
            }
            else {
                if((ch == ')' && st.top() == '(') || (ch == ']' && st.top() == '[') || (ch == '}' && st.top() == '{')) {
                    st.pop();
                }
                else {
                    st.push(ch);
                }
            }
        }
        return st.empty();
    }
};
  • Version 2
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(char ch : s) {
            if(st.empty()) {
                st.push(ch);
            }
            else {
                if((ch == ')' && st.top() != '(') || (ch == ']' && st.top() != '[') || (ch == '}' && st.top() != '{')) {
                    return false;
                }
                else if(ch == ')' || ch == ']' || ch == '}'){
                    st.pop();
                }
                else {
                    st.push(ch);
                }
            }
        }
        return st.empty();
    }
};

Reference

  1. https://leetcode.com/problems/valid-parentheses/description/

相关文章

网友评论

  • 深度沉迷学习:按什么顺序刷的?
    SnailTyan:@深度沉迷学习 随机,做完一个会推荐类似的题目,刷的顺序完全凭心情,😂

本文标题:Leetcode 20. Valid Parentheses

本文链接:https://www.haomeiwen.com/subject/dwiloftx.html