[One question per day] Effective brackets

https://leetcode-cn.com/problems/valid-parentheses/

Given a string containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must meet:

The left bracket must be closed with the same type of right bracket.
The left bracket must be closed in the correct order.
Note that an empty string can be considered a valid string.

Example:
Input: "()"
Output: true
Example 2:

Input: "() [] {}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([]]"
Output: false

Input: "{[]}"
Output: true


Solution 1

60 ms 12 MB
comments from users in the comment area, python version.

class Solution:
    def isValid(self, s):
        while '{}' in s or '()' in s or '[]' in s:
            s = s.replace('{}', '')
            s = s.replace('[]', '')
            s = s.replace('()', '')
        return s == ''

Solution 2

4ms, 6.4mb

Using stack, when a left parenthesis is encountered, a corresponding right parenthesis is pushed onto the stack. If the right parenthesis is encountered, the top element of the stack! = The current right parenthesis, or the current stack is empty (no match) and return false.

class Solution {
public:
    bool isValid(string s) {
        if (s == "") {
            return true;
        }

        stack<char> st;
        for (int i = 0; i < s.size(); ++i) {
            switch(s[i]) {
                case '(':
                    st.push(')');
                    break;
                case '{':
                    st.push('}');
                    break;
                case '[':
                    st.push(']');
                    break;
                default:
                    if (st.empty() || s[i] != st.top()) {
                        return false;
                    } else {
                        st.pop();
                    }
            }
        }
        if (st.empty()) {
            return true;
        } else {
            return false;
        }
    }
};

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105315088