[LeetCode-Simple] 20. Effective Parentheses- Stack

20. Valid Parentheses


Solution: stack

When I saw the problem of matching brackets, my first thought was to use a stack to scan the string. If the current character is ' ( ' ' [ ' ' { ', push it onto the stack, otherwise pop the top of the stack and judge the top of the stack Whether the character matches the current character, if it matches, it will continue to judge the next character, if it does not match, it will return false. Note that there is a case where the first character has nine tails ' ) ' ' ] ' ' } ', which is obviously not Match, so it is necessary to judge whether the current stack is empty before popping the top character of the stack. If it is empty, the string is obviously invalid and returns false

In addition, there are situations such as "[[()", so after scanning the string, it is necessary to judge whether the current stack is empty. If it is empty, it means that the brackets match successfully, the string is valid, and return true; if it is not empty, it means Invalid string, return false

code show as below:

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        stack<char> sta;
        for(int i=0;i<s.length();i++){
    
    
            if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
    
    
                sta.push(s[i]);
            }
            else{
    
    
                if(sta.empty()) return false;
                char temp=sta.top();
                sta.pop();
                if((temp=='('&&s[i]==')') || (temp=='['&&s[i]==']') || (temp=='{'&&s[i]=='}')){
    
    
                    continue;
                }else{
    
    
                    return false;
                }
            }
        }
        if(sta.empty()) return true;
        else return false;
    }
};

In the solution given by Likou, map is used to make the process of judging whether to match more concise. The code is as follows for reference:

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        int n = s.size();
        if (n % 2 == 1) {
    
    
            return false;
        }

        unordered_map<char, char> pairs = {
    
    
            {
    
    ')', '('},
            {
    
    ']', '['},
            {
    
    '}', '{'}
        };
        stack<char> stk;
        for (char ch: s) {
    
    
            if (pairs.count(ch)) {
    
    
                if (stk.empty() || stk.top() != pairs[ch]) {
    
    
                    return false;
                }
                stk.pop();
            }
            else {
    
    
                stk.push(ch);
            }
        }
        return stk.empty();
    }
};

Guess you like

Origin blog.csdn.net/qq_43619058/article/details/125946056