抱歉,代码太乱了,但我有个问题。
我试图解决LeetCode的844任务。它考虑到
给定两个字符串S和T,如果它们是相等的,则在空文本编辑器中输入这两个字符串时返回。#表示退格字符。
第一例
输入:s= "ab#c",T= "ad#c“ 输出:真 说明:科技和科技都变成了“交流”。
第二例
输入:s= "ab##",T= "c#d#“ 输出:真 说明:科技和科技都变成了"“。
我的解决办法是:
class Solution {
public:
bool backspaceCompare(string S, string T) {
vector<char> a;
vector<char> b;
int id = 0;
for(int i = 0; i < S.length(); i++){
a.push_back(S[i]);
id++;
if(S[i]=='#'){
a.erase(a.begin()+id-2);
id--;
a.erase(a.begin()+id-1);
id--;
}
if(S[i+1]=='#'){
a.erase(a.begin()+id-1);
id--;
i+=2;
}
}id = 0;
for(int i = 0; i < T.length(); i++){
b.push_back(T[i]);
id++;
if(T[i]=='#'){
b.erase(b.begin()+id-2);
id--;
b.erase(b.begin()+id-1);
id--;
}
if(T[i+1]=='#'){
b.erase(b.begin()+id-1);
i+=2;
}
}
bool x;
if(a.size()==0) x = true;
else{
for(int i = 0; i < a.size(); i++){
if(a[i]==b[i]) x = true;
else x = false;
}
}return x;
}
};
//Input: S = "ab##", T = "c#d#"
运行时错误消息
================================================================= ==32==ERROR: AddressSanitizer:负大小-param:(size=-1) #8 0x7f585c70d82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) 0x6020000151位于1字节区域右侧的0字节处[0x60200001500x6020000151] 通过线程T0在这里分配: #5 0x7f585c70d82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) ==32==ABORTING
但这给了我这样一个错误。我觉得这里的尺寸都很好。我的错误在哪里?
发布于 2020-04-09 16:50:40
您的代码中有几个问题
int id = 0;
for (int i = 0; i < S.length(); i++){
a.push_back(S[i]);
id++;
if (S[i]=='#'){
a.erase(a.begin()+id-2);
id--;
a.erase(a.begin()+id-1);
id--;
}
if(S[i+1]=='#'){
a.erase(a.begin()+id-1);
id--;
i+=2;
}
}
'#'
作为第一个字符(或额外的'#'
)处理。S[i+1]
不受i == S.size() - 1
约束时i += 2
是在常规++i
之外完成的。您的代码可以通过以下方式简化:
std::string backspace_string_simplification(const std::string& s)
{
std::string res;
for (char c : s) {
if (c != '#') {
res.push_back(c);
} else if (!res.empty()) {
res.pop_back();
}
}
return res;
}
然后,您的“字符串比较”:
bool x;
if (a.size() == 0)
x = true;
else {
for(int i = 0; i < a.size(); i++) {
if(a[i]==b[i]) x = true;
else x = false;
}
}
return x;
a
为空时,如果b
也为空,则字符串等于。a
和b
的大小不同,您可以在循环中退出绑定访问,或者忽略其余的比较(而它应该是假的)。if
等同于x = (a[i] == b[i])
,因此循环等效于(具有正确大小的) x = a.back() == b.back()
。您可以简单地执行return a == b;
( std::string
和std::vector<char>
处理)。
结果是
bool backspaceCompare(string lhs, string rhs) {
return backspace_string_simplification(lhs) == backspace_string_simplification(rhs);
}
https://stackoverflow.com/questions/61125259
复制相似问题