I have problem with my program on C++, witch checks an valid brackets. If i want to check ')', i get segmentation error.
Example:
input: (()) output: Yes
input: (() output: No
input: ()) output: back() called an empty deque(Visual C++)
As i understand it, element of string trying to access an empty stack. How to handle this case?
My code
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool valid_brackets(string& expression)
{
stack<char> brackets;
for (char c : expression)
{
if (c == '(')
brackets.push(c);
else if (c == ')')
{
if (c == ')' && brackets.top() != '(')
return false;
brackets.pop();
}
}
return brackets.empty();
}
int main()
{
string expression;
getline(cin, expression);
if (valid_brackets(expression))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745118972a4612301.html
评论列表(0条)