作为一项额外的编程挑战,我被要求查看大括号是否匹配这样的随机字符串或字符:{1+1} 这将返回 1,而 {1+1}) 将返回 0。这就是我所拥有的到目前为止,但它似乎没有做任何事情。任何帮助都会很棒?谢谢
//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}");
}