string removeDuplicates(string s) {
for(int i = 0; i<s.length(); i++){
int count = 0;
while (s[i-count]==s[i+1+count])
count += 1;
i -= count;
s.erase(i+1,2*count);
cout<<s<<endl;
}
return s;
}
您将得到一个由小写英语字母组成的字符串s。重复删除包括选择两个相邻且相等的字母并删除它们。
我们在s上重复删除,直到我们不能再删除为止。
删除所有重复的字符串后返回最后一个字符串。可以证明答案是唯一的。
这是leetcode问题1047。我的代码在vscode中运行,但是当我提交这个时,我得到了错误。如果您知道错误,请提供帮助。
Line 1065: Char 9: runtime error: addition of unsigned offset to 0x7ffd301f5600 overflowed to 0x7ffd301f55ff (basic_string.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1074:9
1条答案
按热度按时间s5a0g9ez1#
考虑这个字符串
"aa"
发生了什么。首先
i
和count
等于零,所以s[i-count]==s[i+1+count]
为真,所以执行count += 1;
。现在
i
等于0,count
等于1,再次检查s[i-count]==s[i+1+count]
,但这一次i-count
等于-1
,所以您检查s[-1]
,这是非法的,并导致您看到的错误消息。也许
s[i-count]
是s[i+count]
的一个错字,但即使有了这个改变,我也不认为你的程序是正确的。你需要做的是更仔细地考虑你写的代码。每次你写
X[Y]
时,你都必须考虑Y
对于X
来说是太大还是太小。仅仅在大多数时候是正确的是不够的,它必须在所有的时候都是正确的。