given a string, ask for the length of its longest palindrome string.
train of thought: starting from the head of a given string, set two pointers at each character's position, respectively, forward and backward in two directions to determine whether each character is equal, and the length of the palindrome string when the two pointers point to unequal characters. Repeat this process until the last character in the string is scanned.
The two for loops in the inner layer, respectively for the I-centric, odd-and even-numbered cases, the entire code traverses the central position I and expands to find the longest palindrome.
Note: The calculation method of the length of palindrome string
The code is as follows:
Longest palindrome substring
#include <iostream>
using namespace std;
*s is a string, n is the length of the string
int lagpalindrome (char *str, int n)
{
int count = 0;
int max = 0;//length of the longest palindrome string
if (str = NULL | | n<1)
{return
0;
}
for (int i = 0; i < n; i++)
{
//substring is odd for
(int j = 0; (i-j) >=0&& (i+j) <n; J + +)
{
if (Str[i-j]!= str[i + j])
{break
;
}
Count = 2 * j + 1;
}
if (Count > Max)
{
max = count;
}
for
(int k = 0 when substring is even) (i-k) >=0 && (i + k + 1) < n; k++)
{
if (Str[i-k]!= str[i + k+1])
{break
;
}
Count=2*k + 2;
}
if (Count > Max)
{
max =count;
}
}
return max;
}
int main ()
{
char str[] = "ABCCBA";
int n = strlen (str);
int maxlen;
MaxLen = Lagpalindrome (str, n);
cout << The length of the longest palindrome string is: "<<MaxLen<<endl;
return 0;
}