Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取最长回文子字符串的溢出错误_C++ - Fatal编程技术网

C++ 获取最长回文子字符串的溢出错误

C++ 获取最长回文子字符串的溢出错误,c++,C++,错误 编辑:更改s.at而不是s[]后 在Leetcode的编译器中获取此错误,但我的代码在任何在线编译器中都可以正常工作 这是我的密码: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 18446744073709551615) >= this->size() (which is 5) 字符串最长回文(字符串s

错误

编辑:更改s.at而不是s[]后

在Leetcode的编译器中获取此错误,但我的代码在任何在线编译器中都可以正常工作

这是我的密码:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 18446744073709551615) >= this->size() (which is 5)
字符串最长回文(字符串s)
{
int i,j,flag=0;
字符串max_so_far=“”,max_till_now=“”;
如果(s.empty())
返回“”;
如果(s.长度()==1)
返回s;
对于(i=0;ii;j--){
int k=0;
如果(s[i]==s[j]){

当(s[i+k]==s[j-k]&(j-k)>=0&&(i+k)时,你能告诉我你包含的所有库吗?试着用s.at(index)代替
s[index]
,问题变得很明显。IMHO
j-k
取负值,你测试
(j-k)>=0
(i+k)我这边的一个建议是,在下面的while循环中,尝试将最后一个条件作为第一个条件,然后代码应该可以正常运行:-像这样--while((i+k)=0)尝试让我知道这是否对您有效正确缩进代码将是愉快调试会话的第一步。顺便说一下,“最长回文子序列”与“最长回文子串”不同,请确保您解决了正确的问题。即使修复了错误(在“abaa”上进行测试),此算法也不会
string longestPalindrome(string s)
{
    int i, j, flag = 0;
    string max_so_far = "", max_till_now = "";
    if (s.empty())
        return "";
    if (s.length() == 1)
        return s;
    for (i = 0; i < s.length(); i++) {
        max_till_now = "";
        for (j = s.length() - 1; j > i; j--) {
            int k = 0;
            if (s[i] == s[j]) {
                while (s[i + k] == s[j - k] && (j - k) >= 0 && (i + k) <= s.length() - 1) {
                    max_till_now += s[i + k];
                    k++;
                }
            }
            if (!max_till_now.empty())
                break;

            else
                continue;
        }
        if (max_so_far.length() < max_till_now.length()) {
            max_so_far = max_till_now;
        }
    }
    return max_so_far;
}