我正在编写一个程序来检查括号的分数,Leetcode 问题 856。但是,使用我使用的算法,我遇到了“Segmentation Fault (core dumped)”错误。我不确定使用堆栈时如何出现段错误,我该如何解决?
string s;
cin >> s;
int score = 0;
stack<int> st;
for (int i = 0; i < s.size(); i++){
char a = s[i];
if (a == '('){
st.push(score);
score = 0;
}
else{
score = st.top() + max(score*2, 1);
st.pop();
}
}
cout << score;
}
最佳答案
当堆栈为空并且您尝试 .top() 或 .pop() 时,它将给出段错误(由访问内存引起的错误)。
string s;
cin >> s;
int score = 0;
stack<int> st;
for (int i = 0; i < s.size(); i++){
char a = s[i];
if (a == '('){
st.push(score);
score = 0;
}
else if(!st.empty()){
score = st.top() + max(score*2, 1);
st.pop();
}
}
cout << score;
}
关于c++ - 使用 Stack 时的段错误到底是什么以及如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64441129/