21. Effective parentheses

Valid parenthesis

topic

Given a string containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string needs to be satisfied: 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 1:

Input: "()"
Output: true

Example 2:

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

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([]]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Run the code

class Solution {
public:
    bool isValid(string s) {
         stack<char> st;
        st.push('#');
        char c[150];
        c['('] = ')';
        c['{'] = '}';
        c['['] = ']';
        if(s.empty())
            return true;
        for(auto ch : s) {
            if (ch == '(' || ch == '{' || ch == '[')
                st.push(ch);
            else if (c[st.top()] == ch)
                st.pop();
            else 
                return false;
        }
        if(st.top() == '#')
            return true;
        return false;
    }
};

operation result

Insert picture description here

Published 22 original articles · praised 0 · visits 296

Guess you like

Origin blog.csdn.net/qq_45950904/article/details/105033541
21.