c++ - 括号检查器 C++ 程序
问题描述
我只是在学习处理堆栈并尝试解决一些问题。我将极客的这个算法用于极客。在这个括号检查程序中。这为输入 {([])} 返回 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();
}
解决方案
我改成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();
}
推荐阅读
- javascript - Nuxt i18n 在语言切换时重置数据对象
- java - 从按钮单击上的线程值设置 JTextField 不起作用
- python - 更新散景时出现问题:[WinError 126] 找不到指定的模块
- javascript - 无法读取未定义的属性 getExif
- mysql - 计算每个每日活跃用户的平均会话时长?
- c# - 从 Button Form App Visual Studio 调用函数
- github - Github Actions 中的 PR 更新事件
- twilio - Twilio 给一条短信或彩信一个被叫的 id
- python - 如何在 python 中逐行查看程序的执行?
- jasmine - 即使测试通过,Angular in-memory-web-api 方法总是在浏览器的控制台中返回 404 NotFound