我已经被要求作为奖金编程挑战来查看大括号是否匹配随机字符串或像这样的字符:{1 + 1}这将返回1,而{1 + 1})会返回0. 这是我迄今为止的,但它似乎没有做任何事情。任何帮助将是伟大的?谢谢C++检查大括号是否匹配
//bonus.cpp
#include <iostream>
#include <string>
#include <queue>
#include <stack>
using namespace std;
int checkBraces (string s)
{
//int myLength = s.length();
std::stack<int> stack;
char d;
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
if (c == '(')
{
stack.push(c);
}
else if (c == '[')
{
stack.push(c);
}
else if (c == '{')
{
stack.push(c);
}
else if (c == ')')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '(')
{
return false;
}
}
}
else if (c == ']')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '[')
{
return false;
}
}
}
else if (c == '}')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '{')
{
return false;
}
}
}
}
if (stack.empty()) return true;
else return false;
}
int main()
{
cout << "This program checks brace ([{}]) matching in a string." << endl;
checkBraces ("{1+1}");
}
您是否尝试单步执行调试器中的代码以查看实际发生了什么? * –
*似乎没有做任何事情* - 可以在这里使用更多的信息。 –
你有相当多的冗余。也许你应该有一个'bool pop_if_possible(std :: stack,char)'方法,这样你就可以编写'if(c ==')'&&!pop_if_possible(stack,'(')){return false; }' –
MSalters