Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

 
Example

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 

LeetCode上的原题,请参见我之前的博客Valid Parentheses

 

class Solution {
public:
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    bool isValidParentheses(string& s) {
        stack<char> st;
        for (char c : s) {
            if (c == ')' || c == '}' || c == ']') {
                if (st.empty()) return false;
                if (c == ')' && st.top() != '(') return false; 
                if (c == '}' && st.top() != '{') return false;
                if (c == ']' && st.top() != '[') return false;
                st.pop();
            } else {
                st.push(c);
            }
        }
        return st.empty();
    }
};

 

相关文章:

  • 2021-09-27
  • 2022-02-23
  • 2022-12-23
  • 2022-02-09
  • 2021-07-25
  • 2021-09-08
  • 2022-02-14
  • 2021-11-09
猜你喜欢
  • 2021-10-09
  • 2022-12-23
  • 2021-11-10
  • 2021-10-23
  • 2021-12-11
  • 2021-12-29
  • 2021-06-30
相关资源
相似解决方案