SoFunction
Updated on 2025-04-08

Detailed explanation of the code used by C++ to achieve bracket matching using stack

introduction

In programming, parentheses matching is a common problem, especially when dealing with tasks such as mathematical expressions, compiler parsing, etc. Stack is a data structure that is very suitable for dealing with such problems, because the stack has the "Last In First Out" feature, which can accurately manage the matching problems of brackets.

This article will use C++ code to explain in detail how to use the stack to achieve bracket matching, what its principle is, what is the logical structure implementation, and use symbols to represent the status of the stack to help you understand the application of the stack.

Problem description

Given a string containing three types of brackets:()[]. We need to judge whether the brackets in the string are paired correctly. If each left bracket has the corresponding close bracket and the pairing order of the brackets is correct, returntrue; otherwise returnfalse

For example:

  • enter:"[()]", output:true
  • enter:"[(])", output:false

Code explanation

#include "bits/stdc++.h"
using namespace std;

bool search(string str) {
    stack<char> s; // Create a stack to store the left brackets    for(char c : str) { // Iterate through each character in the string        if(c == '[' || c == '(') { // If it is the left bracket, press the stack            (c);
        } else if(()) { // If it is a close bracket, but the stack is empty, it means there is no matching left bracket.            return false;
        } else if(c == ']' && () == '[') { // If it is a close bracket, and the top of the stack is a left bracket            (); // The matching is successful, the top element of the stack is popped up        } else if(c == ')' && () == '(') { // If it is a close bracket, and the top of the stack is a left bracket            (); // The matching is successful, the top element of the stack is popped up        } else {
            return false; // If the closing bracket does not match the top of the stack, return false        }
    }
    return (); // If the stack is empty, all brackets match successfully, return true; otherwise, return false}

int main() {
    cout << search("[])" ) << endl; // Test input    return 0;
}

Code parsing

  1. Stack initialization
    existsearchWhen the function starts, we create a stack of character types.s, used to store the left brackets encountered'('and'['

  2. Iterate over strings
    We passedfor (char c : str)Iterate through each character in the string.

  3. Left bracket processing
    If the current character is left bracket'('or'[', we push it into the stack.

  4. Close bracket processing
    If the current character is a close bracket')'or']', we first check whether the stack is empty:

    • If the stack is empty, it means there is no matching opening bracket, so returnfalse
    • Otherwise, we check whether the top element on the stack is the corresponding left bracket. If it matches, the top element of the stack is popped up, indicating that the pair of brackets has been matched successfully.
    • If it does not match, returnfalse, indicating that the bracket order is incorrect.
  5. Check if the stack is empty
    After the traversal is completed, if the stack is empty, it means that all brackets match successfully. Otherwise, returnfalse, means there are still no matching left brackets.

The status representation of the stack

To facilitate understanding of stack changes, we use symbols to represent the status of the current stack. The elements of the stack are arranged in order from the bottom of the stack to the top of the stack.

Example 1: Input"[()]"

  1. Initial state: stack is empty:[]
  2. Processing characters'[', press it on the stack:['[']
  3. Processing characters'(', press it on the stack:['[', '(']
  4. Processing characters')', the top of the stack is'(', match successfully, pop up the top of the stack:['[']
  5. Processing characters']', the top of the stack is'[', match successfully, pop up the top of the stack:[]
  6. The final stack is empty, all brackets match successfully, returntrue

Example 2: Input"[(])"

  1. Initial state: stack is empty:[]
  2. Processing characters'[', press it on the stack:['[']
  3. Processing characters'(', press it on the stack:['[', '(']
  4. Processing characters')', the top of the stack is'(', match successfully, pop up the top of the stack:['[']
  5. Processing characters']', the top of the stack is'[', match successfully, pop up the top of the stack:[]
  6. The final stack is empty, all brackets match successfully, returntrue, but in fact, the bracket order is wrong, the program should returnfalse

test

cout << search("[])" ) << endl; // Test input

For input"[])", the execution process of the program is as follows:

  1. Initial state: stack is empty:[]
  2. Processing characters'[', press it on the stack:['[']
  3. Processing characters']', the top of the stack is'[', match successfully, pop up the top of the stack:[]
  4. Processing characters')', the stack is empty, indicating that there is no matching left bracket, returnfalse

Summarize

Through this code and symbolized stack state representation, you can clearly understand the application of the stack in bracket matching. The "last in first out" feature of the stack makes it very suitable for solving parentheses pairing problems. In actual programming, the stack can also be used in many other scenarios, such as function call management, depth-first search, etc.

The above is the detailed explanation of the code for C++ using stack to achieve bracket matching. For more information about C++ stack to achieve bracket matching, please pay attention to my other related articles!