我正在尝试提交有关leetcode的解决方案,当我提交它时,这会给我一个运行时错误。
AddressSanitizer: stack-buffer-overflow on address 0x7ffd6484f411 at pc 0x000000386795 bp 0x7ffd6484ed70 sp 0x7ffd6484ed68
这是我的代码:
int lengthOfLongestSubstring(std::string s)
{
auto start = std::begin(s);
std::string substring = std::string(std::begin(s), std::begin(s) + 1);
std::string pre_string = std::string(std::begin(s), std::begin(s) + 1);
for (auto itr = std::begin(s) + 1; itr != std::end(s); ++itr)
{
auto next = itr;
if (std::find(std::begin(substring), std::end(substring), *itr) ==
std::end(substring))
{
substring = std::string(start, itr + 1);
}
else
{
if (++next != std::end(s))
{
start = itr;
pre_string = substring;
substring = std::string(itr, ++itr);
}
}
}
if (pre_string.length() > substring.length())
{
return pre_string.length();
}
else
return substring.length();
}
当我尝试在计算机上运行它时,它不会给我任何警告。运行完全正常。
我正在使用以下命令。
g++ -Wall -Wpedantic longestString.cpp -o long.o
然后我使用valgrind
来查看任何问题,但它也表示没有问题,因为您可以看到输出。
username@droozal:~/leetcode$ valgrind ./long.o
==9473== Memcheck, a memory error detector
==9473== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9473== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==9473== Command: ./long.o
==9473==
5
==9473==
==9473== HEAP SUMMARY:
==9473== in use at exit: 0 bytes in 0 blocks
==9473== total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==9473==
==9473== All heap blocks were freed -- no leaks are possible
==9473==
==9473== For counts of detected and suppressed errors, rerun with: -v
==9473== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
所以我的问题是潜在的错误是什么?我的代码有问题吗?还是什么?答案将不胜感激。谢谢。
答案 0 :(得分:0)
我想,我看到您正在尝试用恒定的内存来解决。您可以使用备忘录,但是对于此问题,代码/调试要简单得多。
这将通过:
#include <string>
#include <map>
#include <algorithm>
class Solution {
public:
static inline int lengthOfLongestSubstring(const std::string s) {
map<char, int> char_map;
int start = -1;
int longest = 0;
const int length = s.size();
for (int index = 0; index < length; index++) {
if (char_map.count(s[index]) != 0) {
start = std::max(start, char_map[s[index]]);
}
char_map[s[index]] = index;
longest = std::max(longest, index - start);
}
return longest;
}
};