[英]Parenthesis Checker C++ program
I'm just learning to deal with stack and trying to implement some questions.我只是在学习处理堆栈并尝试解决一些问题。 I used this algorithm from geeks for geeks.
我将极客的这个算法用于极客。 In this Parenthesis Checker program.
在这个括号检查程序中。 This is returning false for the input {([])} Can somebody please help why.
这为输入 {([])} 返回 false 有人可以帮忙解释一下原因吗?
bool ispar(string x)
{
// Your code here
stack<int> s;
for(int i=0;i<x.size();i++){
if(x[i]=='{' || x[i]=='[' || x[i]=='('){
s.push(x[i]);
continue;
}
if(s.empty()){
return false;
}
switch(x[i]){
case ')':{
x = s.top();
s.pop();
if (x[i]=='{' || x[i]=='[')
return false;
break;
}
case '}':{
x = s.top();
s.pop();
if(x[i] =='[' || x[i]=='(')
return false;
break;
}
case ']':{
x = s.top();
s.pop();
if(x[i] == '(' || x[i] =='{')
return false;
break;
}
}
}
return s.empty();
}
I changed stack<int>
to stack<char>
, and s.top()
must be assigned to a char
, not string x
.我将
stack<int>
更改为stack<char>
,并且s.top()
必须分配给char
,而不是string x
。
bool ispar(const std::string& x)
{
// Your code here
stack<char> s;
char opening_char;
for (int i = 0; i < x.size(); i++) {
if (x[i] == '{' || x[i] == '[' || x[i] == '(') {
s.push(x[i]);
continue;
}
if (s.empty()) {
return false;
}
switch (x[i]) {
case ')': {
opening_char = s.top();
s.pop();
if (x[i] == '{' || x[i] == '[')
return false;
break;
}
case '}': {
opening_char = s.top();
s.pop();
if (x[i] == '[' || x[i] == '(')
return false;
break;
}
case ']': {
opening_char = s.top();
s.pop();
if (x[i] == '(' || x[i] == '{')
return false;
break;
}
}
}
return s.empty();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.