Bracket matching problem: clever application of stack and code optimization [stack, optimization, hash table]

When solving algorithmic problems, flexible use of data structures is crucial. In this problem, we need to determine whether a string containing only brackets is valid, that is, whether the brackets can be matched and closed correctly. This problem can be solved well using this data structure.

Question link: valid parentheses

Problem-solving ideas: Why use a stack?

The bracket matching problem requires determining whether the brackets in the input string are correctly closed , and the order of the brackets must also be correct. In this case, we can use 堆栈.

The stack is a 后进先出(LIFO)data structure that is very suitable for solving bracket matching problems.

When we encounter a left parenthesis , we 压入stack it, and when we encounter a right parenthesis , we can 弹出stack the top element and compare for a match.

original code

First, let's take a look at the original solution code:

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

optimized code

In order to simplify the logic and improve the readability of the code, we can use a hash table to store the correspondence between brackets and improve it in conjunction with the basic operations of the stack:

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        stack<char> st;
        unordered_map<char, char> mapping = {
    
    
            {
    
    ')', '('},
            {
    
    ']', '['},
            {
    
    '}', '{'}
        };
        
        for (char c : s) {
    
    
            if (c == '(' || c == '[' || c == '{') {
    
    
                st.push(c);
            } else {
    
    
                if (st.empty() || st.top() != mapping[c]) {
    
    
                    return false;
                }
                st.pop();
            }
        }
        
        return st.empty();
    }
};

Tips for using the basic operations of the stack

When solving this problem, we made full use of the basic operations of the stack:

  1. push: Push the left bracket onto the stack.
  2. pop: When a right bracket is encountered, pop it off the stack and compare it with the current right bracket to see if it matches.
  3. top: Check whether the top element of the stack matches the current right bracket.

These operations allow us to efficiently check whether the brackets match.

Summary and reflection

The bracket matching problem is a typical problem solved using stack. By pushing the left parenthesis onto the stack and then performing a pop match when the corresponding right parenthesis is encountered, we can effectively determine whether the parenthesis is closed correctly.

The original code did its job, but existed 冗长的 if-else 语句and was not elegant enough. By using 哈希表stored bracket correspondence, we can accomplish the same function with more concise code, improving the readability and maintainability of the code.

The bracket matching problem is just a small application of the stack in algorithms. The stack has many other powerful uses, such as reverse Polish expression evaluation , depth-first search , etc. Mastering the basic operations and flexible applications of the stack is very helpful to improve your understanding of algorithms and data structures.

Guess you like

Origin blog.csdn.net/qq_22841387/article/details/132218686