作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
有人问过类似的问题。这个问题是常见的寻找最长回文子串的问题。
在读取错误转储时遇到一些问题,我想我有一个数组索引超出范围的错误,但无法使用我的日志、输出语句和查看我的条件检查来跟踪它。添加注释以表示行号。在 Windows 的 Linux 子系统上运行它。
输出
> valgrind --track-origins=yes ./a.out
==665== Memcheck, a memory error detector
==665== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==665== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==665== Command: ./a.out
==665==
==665== error calling PR_SET_PTRACER, vgdb might block
==665== Conditional jump or move depends on uninitialised value(s)
==665== at 0x401C00: Solution::longestPalindrome(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:61)
==665== by 0x400F05: main (main.cpp:79)
==665== Uninitialised value was created by a stack allocation
==665== at 0x401752: Solution::longestPalindrome(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:28)
==665==
aaaabbaa HAS: aabbaa <-
代码
class Solution
{
public:
std::pair<int,int> expandFrom(const std::string s, int left_char, int right_char, const int str_len)
{
while(left_char >= 0 && right_char <= str_len && s[left_char] == s[right_char]) {
--left_char;
++right_char;
}
return {left_char+1, right_char-1};
}
const std::string longestPalindrome(const std::string s) // line 28
{
if(s.length() == 0 || s.length() >= 1000) { return ""; }
else if(s.length() == 1) { return s; }
const int str_length = s.length();
std::string longest_palindrome = "";
std::pair<int, int> range1 = {0,0};
std::pair<int, int> range2 = {0,0};
int length1 = 0;
int length2 = 0;
for(int mid = 0; mid < str_length; ++mid) {
range1 = expandFrom(s, mid, mid, str_length);
range2 = expandFrom(s, mid, mid+1, str_length);
length1 = range1.second - range1.first;
length2 = range2.second - range2.first;
if (length1 > length2) {
if (length1 > longest_palindrome.length()) {
longest_palindrome = s.substr(range1.first, range1.second);
if(longest_palindrome[range1.first] != longest_palindrome[range1.second]) {
longest_palindrome = s.substr(range1.first, range1.second + 1);
}
}
} else {
if (length2 > longest_palindrome.length()) { // line 61
longest_palindrome = s.substr(range2.first, range2.second);
if(longest_palindrome[range2.first] != longest_palindrome[range2.second]) {
longest_palindrome = s.substr(range2.first, range2.second + 1);
}
}
}
}
return longest_palindrome;
}
};
int main()
{
Solution s;
std::cout << "aaaabbaa HAS: " << s.longestPalindrome("aaaabbaa") << " <-\n\n"; // line 79
}
最佳答案
你的代码逻辑显然是错误的...
您的代码执行语句:
longest_palindrome = s.substr(range2.first, range2.second);
所以 longest_palindrome
现在是一个长度为 range2.second - range2.first
的字符串,有效索引从 0
到 range2 .second - range2.first - 1
包含在内。
在下一条语句中,您将使用 range2.first
和 range2.second
作为索引来访问它。
关于c++ - 回文程序和条件跳转或移动取决于未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621159/
我是一名优秀的程序员,十分优秀!