Stack Application: Bracket Matching Animation Demo Visualize your code with animations

图码-数据结构可视化动画版

给定一个表达式字符串 exp ,编写一个程序来检查给定表达式中“{”, “}”, “(”, “)”, “[”, “]”的对和顺序是否正确。

示例 : 

输入 :exp = “[()]{}{[()()]()}” 
输出 :Balanced
解释: 所有括号格式正确

输入 :exp = “[(])” 
输出 :Not Balanced 
解释:1 4 括号不平衡,因为 
在右括号 '(' 之前有一个右括号 ']'

使用Stack 检查平衡括号表达式

这个想法是将所有左括号放入堆栈中。 每当您击中右括号时,请搜索堆栈顶部是否是相同性质的左括号。 如果成立,则弹出堆栈并继续迭代。 最后如果堆栈为空,则意味着所有括号都是平衡的或格式良好的。 否则,它们就不平衡。

插图: 
下面是上述方法的插图。

请按照下面提到的步骤来实现这个想法:

  • 声明一个字符 堆栈 (例如 temp )。
  • 现在遍历字符串exp。 
    • 如果当前字符是起始括号( '(' 或 '{' 或 '[' ),则将其压入堆栈。
    • 如果当前字符是右括号( ')' 或 '}' 或 ']' ),则从堆栈中弹出,如果弹出的字符是匹配的起始括号,则可以。
    • 否则括号 不平衡
  • 完成遍历后,如果堆栈中留下一些起始括号,则表达式为 Not Balanced ,否则为 Balanced

下面是上述方法的实现:

C++

// C++ program to check for balanced brackets.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if brackets are balanced
bool areBracketsBalanced(string expr)
{
    // Declare a stack to hold the previous brackets.
    stack<char> temp;
    for (int i = 0; i < expr.length(); i++) {
        if (temp.empty()) {
             
            // If the stack is empty
            // just push the current bracket
            temp.push(expr[i]);
        }
        else if ((temp.top() == '(' && expr[i] == ')')
                 || (temp.top() == '{' && expr[i] == '}')
                 || (temp.top() == '[' && expr[i] == ']')) {
             
            // If we found any complete pair of bracket
            // then pop
            temp.pop();
        }
        else {
            temp.push(expr[i]);
        }
    }
    if (temp.empty()) {
         
        // If stack is empty return true
        return true;
    }
    return false;
}
 
// Driver code
int main()
{
    string expr = "{()}[]";
 
    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}


            

C

Java

Python3

C#

JavaScript

输出

均衡

时间复杂度: O(N),对大小为 N 的字符串迭代一次。
辅助空间: 堆栈的 O(N)。 

在不使用堆栈的情况下检查平衡括号表达式:

以下是应遵循的步骤:

  • -1 初始化变量 i
  • 遍历字符串并 
    • 如果它是左括号,则将计数器加 1,并将 字符串中的 第 i 个字符替换为左括号。
    • 否则,如果它是相同的相应左括号(左括号存储在 exp[i] 中)的右括号,则将 i 减1。
  • 最后,如果我们得到 i = -1 ,那么字符串是平衡的,我们将返回 true。 否则,该函数将返回 false。

下面是上述方法的实现:

C++

#include <iostream>
 
using namespace std;
 
 bool areBracketsBalanced(string s) {
        int i=-1;
        for(auto& ch:s){
            if(ch=='(' || ch=='{' || ch=='[')
                s[++i]=ch;
            else{
                if(i>=0 && ((s[i]=='(' && ch==')') || (s[i]=='{' && ch=='}') || (s[i]=='[' && ch==']')))
                    i--;
                else
                    return false;
            }
        }
        return i==-1;
    }
 
int main()
{
    string expr = "{()}[]";
 
    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}


            

Java

C#

Python3

JavaScript

输出

均衡

时间复杂度 :O(N),对大小为 N 的字符串迭代一次。
辅助空间 :O(1)


Whether your goal is exam success, career development, or pure interest, this data structure and algorithm visualization website will be an invaluable resource.

Go to this website and start your learning journey!

These are common ones: [C Language Description] Data Structures and Algorithms Data Structure JAVA Implementation Fundamentals of Data Structures and Algorithms (Qingdao University - Wang Zhuo) Data Structures and Algorithms Wangdao Data Structure C Language Implementation Crash Course Data Structures Final Exam Rescue Data Structure Video C Language Edition Tutorial Data Structure Yan Weimin Data Structure Hao Bin Data Structure Postgraduate Entrance Exam JAVA Data Structure Algorithms and Fundamentals Data Structure Wangdao 2022 Data Structure Learning Data Structure Little Turtle Wang Zhuo Learning Data Structure Data Structure Zhejiang University Data Structure Review Data Structure Ma Soldier Data Structure Zero-Based Tutorial Data Structures and Algorithms Data Structure Introduction Postgraduate Data Structure Exercise Explanation Data Structure Final Review Computer Level 2