Given a string s to find the longest palindrome substring in s, you can assume that the maximum length of S is 1000.

Source: Internet
Author: User
Tags first string

Find the largest palindrome string in a string

Idea: Starting with the first string, once to the left and right, if the same, continue to the left to the right until it is not the same or out of bounds, and determine the maximum length, update the maximum length value, and record the maximum length value of the beginning. The sample code is as follows:

	private int lo, maxlen;

	Public String Longestpalindrome (string s) {
		int len = s.length ();
		if (Len < 2)
			return s;
		
	    for (int i = 0; i < len-1; i++) {
	     	Extendpalindrome (s, I, I);  Assume odd length, try to extend palindrome as possible//extendpalindrome
	     	(s, I, i+1);//assume even length.
	    }
	    return s.substring (lo, lo + maxlen);
	}

	private void Extendpalindrome (String s, int j, int k) {while
		(J >= 0 && K < s.length () && s.ch Arat (j) = = S.charat (k)) {
			j--;
			k++;
		}
		if (MaxLen < k-j-1) {
			lo = j + 1;//marks the start of the maximum length
			maxlen = k-j-1;
		}
	}
	 public static void Main (string[] args) {
		String str = "Bcaba";
		Test15 ts =new Test15 ();
		String s =ts.longestpalindrome (str);
		System.out.println (s);
	}


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.