在 C++ 中检查表达式中括号是否平衡
假设我们有一个表达式。表达式中包含一些括号;我们需要检查括号是否平衡。括号的顺序为 ()、{} 和 []。假设有两个字符串。“()[(){()}]” 是有效的,但“{[}]” 是无效的。
任务很简单;我们将使用栈来完成此操作。我们应该遵循以下步骤来获得解决方案 -
- 遍历表达式,直到它被遍历完
- 如果当前字符是左括号,如 (、{ 或 [,则将其压入栈中
- 如果当前字符是右括号,如 )、} 或 ],则从栈中弹出,并检查弹出的括号是否与当前字符对应的起始括号,如果是,则没问题,否则表示不平衡。
- 字符串遍历完成后,如果栈中还存在一些起始括号,则表示字符串不平衡。
示例
#include <iostream>
#include <stack>
using namespace std;
bool isBalancedExp(string exp) {
stack<char> stk;
char x;
for (int i=0; i<exp.length(); i++) {
if (exp[i]=='('||exp[i]=='['||exp[i]=='{') {
stk.push(exp[i]);
continue;
}
if (stk.empty())
return false;
switch (exp[i]) {
case ')':
x = stk.top();
stk.pop();
if (x=='{' || x=='[')
return false;
break;
case '}':
x = stk.top();
stk.pop();
if (x=='(' || x=='[')
return false;
break;
case ']':
x = stk.top();
stk.pop();
if (x =='(' || x == '{')
return false;
break;
}
}
return (stk.empty());
}
int main() {
string expresion = "()[(){()}]";
if (isBalancedExp(expresion))
cout << "This is Balanced Expression";
else
cout << "This is Not Balanced Expression";
}输出
This is Balanced Expression
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP