The longest palindrome string (c + +) __c++

Source: Internet
Author: User

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.