为什么我在这个函数中得到一个越界异常
Why do I get an out of bounds exception in this function?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int findpali (string s,int dp[][100],int st, int e);
int main (void)
{
string s;
cin>>s;
int dp[100][100];
for (int i = 0; i < 100; i++ )
for ( int j = 0; j < 100; j++ )
dp[i][j] = -1;
int out = findpali(s,dp,0,s.length()-1);
cout<<out<<"n";
return 0;
}
int findpali (string s,int dp[][100],int st, int e) // st ->starting position, e -> ending position
{
if (s.length() == 1)
{
dp[st][e] = 1;
return 1;
}
else if (s.length()==2 && s[st] == s[e])
{
dp[st][e] = 2;
return 2;
}
else if (dp[st][e] != -1)
return dp[st][e];
else if (s[st] == s[e])
{
dp[st][e] = findpali(s.substr(st+1,s.length()-2),dp,st+1,e-1)+2;
return dp[st][e];
}
else
{
dp[st][e] = max(findpali(s.substr(st,s.length()-1),dp,st,e-1),findpali(s.substr(st+1,s.length()-1),dp,st+1,e));
return dp[st][e];
}
}
上面的函数查找给定字符串中最长回文的长度。我已经将给定的数组dp
初始化为-1
,然后我将不同的值存储在数组中。然而,当我输入像ABCD
这样的字符串时,它说超出边界异常并中止。这可能是什么原因呢?谢谢!
您需要在函数的开始添加空字符串的测试。此外,您正在为原始string s
存储dp
,因此当您使用子字符串s更新它时,结果不再有效。你可以在每次递归调用函数时传递不同的索引st and e
。
修改后的函数可能看起来像这样:
int findpali(string &s, int dp[][100], int st, int e)
{
if(s.length()==0 || st > e) { //extra test for boundary case
return 0;
}
if(st==e) // length 1 substring
{
dp[st][e]=1;
return 1;
} else if(e-st==1 && s[st] == s[e]) // length 2 substring
{
dp[st][e]=2;
return 2;
} else if(dp[st][e] != -1)
return dp[st][e];
else if(s[st] == s[e])
{
dp[st][e]=findpali(s, dp, st+1, e-1)+2;
return dp[st][e];
} else
{
dp[st][e]=max(findpali(s, dp, st, e-1), findpali(s, dp, st+1, e));
return dp[st][e];
}
}
相关文章:
- 我在c++代码中生成了一个运行时#3异常
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 如何构建一个异常类来报告C++中的哪些文件和行号?
- 我正在尝试创建一个使用 c++ 中的参数包构造函数的异常类
- 带有Cuda的LibTorch(C++)引发了一个异常
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- 异常对象的最后一个潜在销毁点
- 声明一个额外的变量会导致运行时出现异常
- C++:为什么当我想输入"q"退出时,这会给我一个异常抛出错误?
- 使用一个微不足道的异常类有什么意义
- 我可以让虚拟抽象类抛出一个异常吗?
- 我想捕获一个异常,并将其绑定到我自己的异常中,然后向上抛出
- 我可以有一个异常的静态全局实例吗?
- 在catch块中抛出一个异常会导致两个异常在飞行中吗
- 我使用 POCO 解析 JSON.它抛出一个异常:JSON 异常:错误字符.如何处理汉字
- 我应该返回一个值还是抛出一个异常…
- 当一个异常对象被销毁时(它可以被控制吗)
- 你能把一个异常继承层次结构包装到另一个吗?——或者,另一种干净的处理方式
- 为什么空指针解引用不是一个异常