问题描述
我正在编写一个程序来检查括号的得分,Leetcode问题856。但是,使用我使用的算法时,我遇到了“分段错误(核心被丢弃)”错误。我不确定使用堆栈时如何出现分段错误,如何解决?
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;
}
,
当您的程序尝试访问超出数组大小范围的内存位置时,发生分段错误。 要解决此问题,您必须检查是否正在访问从0到sizeOfArray-1的大小(即)的数组。
您可以使用条件是否存在来检查此条件。好吧,这取决于您要通过程序实现的目标。
,我们也可以不使用堆栈来解决此问题:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
static const struct Solution {
using ValueType = std::uint_fast16_t;
static const int scoreOfParentheses(
const std::string S
) {
ValueType scores = 0;
ValueType level = 0;
for (ValueType index = 0; index < std::size(S); ++index) {
if (S[index] == '(') {
++level;
} else {
--level;
}
if (S[index] == ')' && S[index - 1] == '(') {
scores += 1 << level;
}
}
return scores;
}
};