Palindrome re-visited
I am searching an efficient algorithm to find all the palindromes in a string(actually I have to find the largest palindrome in a string)..
Here is my code
string palindrome(string str)
{
int n=sz(str);
for(int l=n-1;l>=0;l--)//Palindrome can be of any size.
{
for(int i=0;i<n-l+1;i++)
{
int j=i+l-1;
string str2=str.substr(i,j-i+1);
if(check_pal(str2)) return str2;//check_pal simply checks whether //the string is palindrome or not.
}
}
string t1="";
return t1;
}
This is an O(n^3)(since check_pal requires another loop),I searched and got this: http://johanjeuring.blogspot.com/2007/08/finding-palindromes.html
But I cant understand a word of it What is his algo? How is it linear?
Please help me...
shankhs
Junior Poster in Training
58 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1
Hey guys Please help me...
I am new to algorithms if there is an algorithm to find longest palindrome in a string just give me a link thats enough I will try my best to understand that.
Thankyou.
shankhs
Junior Poster in Training
58 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1
Looks like that was his PHD thesis , you may not be able to understand it at all.
ithelp
Nearly a Posting Maven
2,230 posts since May 2006
Reputation Points: 769
Solved Threads: 128
Can i get another algorithm???
shankhs
Junior Poster in Training
58 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1
From the link you posted:
That shouldn't be much difficult to implement, and
Give it a try and then post your efforts in case you need help.
If you see the code in my first post I have done exactly that .the first loop determines the length of the substring to be checked and the second loop checks for each position in the array to get the substring of the specified length.
But this is giving me TLE..I need to optimize it.
shankhs
Junior Poster in Training
58 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1
Or...
bool check(const std::string str, const std::string ori)
{
return ((stricmp(str.c_str(),ori.c_str())==0)?true:false);
}
std::string palindrome(const std::string str)
{
int size=str.length();
std::string reverse_str;
for(int i=((size)-1);i>=0;i--)
reverse_str.push_back(str[i]);
if(check(reverse_str,str))
return reverse_str;
return "it's not a palindrome";
}
int main()
{
std::string m_str=palindrome("dlrow olleh hello world");
std::cout<<m_str.c_str();
std::cin.get();
return 0;
}
My problem is to find longest substring that is a palindrome not to check whether the string is palindrome or not.
shankhs
Junior Poster in Training
58 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1