#include<string>
#include<iostream>
#include<stack>
using namespace std;
bool isbalanced(const string& str)
{
int len = str.size();
stack<char> mystack;
for (int i = 0; i < len; i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<')
mystack.push(str[i]);//将左括号压入栈中
if (str[i] == ')' || str[i] == ']' || str[i] == '}' || str[i] == '>')
{
if (mystack.empty())//如果栈为空,说明没有左括号与右括号匹配,直接返回false
{
cout << "The string is not balanced.You have more closing brackets than opening brackets." << endl;
exit(0);
}
switch (str[i])
{
case ')':
{
if (mystack.top() != '(')
return false;mystack.pop(); break;
}
case ']':
{
if (mystack.top() != '[')
return false;mystack.pop(); break;
}
case '}':
{
if (mystack.top() != '{')
return false;mystack.pop(); break;
}
case '>':
{
if (mystack.top() != '<')
return false;mystack.pop(); break;
}
}
}
}
if (mystack.empty())//N.empty()返回的是一个bool值
return true;
else
return false;
}
int main()
{
bool bal;string str;
cin >> str;
bal = isbalanced(str);//调用函数
if (bal)
cout << "The string is balanced." << endl;
else
cout << "The string is not balanced." << endl;
return 0;
}
标签:cout,示例,int,括号,用栈,str,CPP,mystack,include
From: https://blog.csdn.net/ygklwyf/article/details/143448967