Leetcode 20. Valid Parentheses

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

1. Description

Leetcode 20. Valid Parentheses_第1张图片
Valid Parentheses

2. Solution

  • Version 1
class Solution {
public:
    bool isValid(string s) {
        stack 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 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/

你可能感兴趣的:(Leetcode 20. Valid Parentheses)