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.