点击查看代码
//Check for balanced parentheses using stack
#include<iostream>
#include<stack>//stack from standard template library(STL)
#include<string>
using namespace std;
bool arepair(char opening, char closing) {
if (opening == '(' && closing == ')') return true;
else if (opening == '{' && closing == '}') return true;
else if (opening == '[' && closing == ']') return true;
return false;
}//判断是否匹配
bool AreParanthesesBalanced(string exp) {
stack<char> S;
for (int i = 0; i < exp.length(); i++) {//遍历整个字符串,只关心括号即可
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')//开括号push
S.push(exp[i]);
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']')//闭括号两种情况
{
if (S.empty() || !arepair(S.top(), exp[i]))//stack为空或者与上一括号不匹配
return false;
else
S.pop();//匹配时pop掉上一括号
}
}
return S.empty() ? true : false;//检测最终stack是否为空
}
int main() {
string expression;
cin >> expression;
if (AreParanthesesBalanced(expression))
cout << "balanced" << endl;
else cout << "not balanced" << endl;
}