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