Reputation: 1464
#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];
}
}
The above function finds the length of the longest palindrome in a given string. I have initialised the given array dp
to -1
and then I am storing the different values in the array. However, when I enter a string like ABCD
, it says out of bound exception and it aborts. What could be the reason for this? Thanks!
Upvotes: 0
Views: 63
Reputation: 3580
you need to add test for empty string at the start of your function. Also you are storing dp
for original string s
, so when you update it with a substring of s the result is no longer valid. You can just pass different indices st and e
every time you call the function recursively.
Your modified function may look something like this:
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];
}
}
Upvotes: 1