Given A string S , find the longest palindromic substring in S . Assume that maximum length of S are, and there exists one unique Lon Gest palindromic substring.
Test instructions: Finding the longest palindrome in a character string
Feel this problem is not difficult, you can think of, set two pointers, respectively, corresponding to 0,len-1.
For example, starting with the first character, AbababAC, we can find a where a appears, and then take the first a with each a as a paragraph.determine if each paragraph isIt's a palindrome, because it's looking forward from the back,So the first one to find is definitely the longest palindrome in this search, then the 2nd character and the 3rd character at a time. This idea is better when the characters in the string are different. But if the characters appear for exampleaaaaaabcaaaaa So, in Leetcode a test, Sure enough Timelimited .
second idea ,< Span style= "font-family: ' Helvetica Neue ', Helvetica,arial,sans-serif" > character is Odd time is a, even when the time is two. Each side of the center is matched to determine whether it is equal, thus calculating the length of the palindrome.
code as follows:
public static String Longestpalindrome (string s) {if (S.isempty () | | | S.length () ==1) return s; String longest=s.substring (0,1); for (int i=0;i<s.length (); i++) {//takes I as the center, gets the longest string tmp=ispalindrome (s,i,i); if (Tmp.length () >longest.length ()) longest=tmp; Take i,i+1 as the center, get the longest string tmp=ispalindrome (s,i,i+1); if (Tmp.length () >longest.length ()) longest=tmp; } return longest; }private static string Ispalindrome (string s, int start, int end) { &nbs p;//TODO auto-generated Method stub while (start>=0&&end<= S.length () -1&&s.charat (start) ==s.charat (end)) { start--; end++; } Return s.substring (start+1,end); }
[Java] LeetCode5 Longest palindromic Substring