#include<iostream>
#include<string>
#include<vector>
using namespace std;
int balanceParentheses(string str)
{
vector<char> cvec;
int count = 0;
for (string::size_type i = 0; i < str.size(); ++i)
{
if (str[0] == ')' && cvec.empty())
{
cvec.push_back(str[i]);
}
if (str[i] == '(')
{
cvec.push_back(str[i]);
}
if (str[i] == ')' && !cvec.empty())
{
cvec.erase(cvec.end() - 1);
++count;
}
}
if (cvec.empty())
return count;
else
return -1;
}
int main()
{
string str;
cin >> str;
cout << balanceParentheses(str);
}
百度笔试题:求平衡()个数
最新推荐文章于 2019-08-23 23:29:09 发布
本文介绍了一个C++函数,用于检查并计算输入字符串中平衡的括号对数量。如果字符串开始处存在右括号或者最终未匹配的括号存在,则返回-1。此函数使用了栈的概念来实现。
4738

被折叠的 条评论
为什么被折叠?



