LeetCode-5 longest palindromic Substring (longest palindrome substring)

Source: Internet
Author: User

Given A string S, find the longest palindromic substring in S. The maximum length of S is assume, and there exists one unique longest palindromic substring.

Java:

public class Solution {public static string Longestpalindrome (string s) {string S1 = "";
		String s2 = "";
		int max = 0;
		int temp = 0;
		int iflag = 0;
			for (int i = 0; i < s.length (); i++) {//palindrome number is an odd number of cases.
					for (int j = 1; i-j >= 0 && i + J <= s.length ()-1; j + +) {if (S.charat (i + j) = = S.charat (i-j))
				temp++;
				else {break;
				}} if (Temp > max) {max = temp;
			Iflag = i;
		} temp = 0;

		} S1 = s.substring (Iflag-max, Iflag + max + 1);
		max = 0;
		temp = 0;
		Iflag = 0;
			for (int i = 0; i < s.length (); i++) {//palindrome number is an even number of cases. for (int j = 0; i-j >= 0 && i + j + 1 <= s.length () 1; j + +) {if (S.charat (i-j) = = S.charat (i + j
				+ 1)) temp++;
				else {break;
				}} if (Temp > max) {max = temp;
			Iflag = i;
		} temp = 0;
		} s2 = s.substring (Iflag-max +1, Iflag + max + 1);
	Return S1.length () >s2.length ()? s1:s2;//returns the longer one of the two. }
}

runtime:245 ms

Analysis:

Two cases are dealt with separately, the palindrome number is odd number, palindrome number is even number of cases (because they determine the conditions are different, specifically refer to my code above).

The comparison should be taken into account for the substring position of the two cases.


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.