Longest palindromic Substring
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.
Ideas:
The first thing I wanted to do was to get all the strings out of the way. I drew it on the back of the paper and thought of a way
Traverse the entire string I
1. If S.charat (i) = = S.charat (i + 1), with I and i+1 as the center to both sides of the expansion, if it is a palindrome and longer than the longest palindrome result has been obtained, update result
2. If S.charat (i-1) = = S.charat (i + 1), with i-1 and I + 1 centered on both sides of the expansion, if it is a palindrome and longer than the obtained palindrome result, update result
End of traversal returns result
1 Public classSolution {2 Publicstring Longestpalindrome (string s) {3 if(0 = = s.length () | | 1 = =s.length ())4 returns;5 Else{6String result = "";7 8 for(inti = 0; I < s.length (); i++){9 if(i + 1 < s.length () && s.charat (i) = = S.charat (i + 1)) {//centered on I and i + 1Ten intj = i + 1; One intK =i; A //i = i; - while(k >= 0 && J < s.length ()) {//extend both sides of the center - if(S.charat (k) = =S.charat (j)) { the if((j-k + 1) > Result.length ())//only bigger to update -result = S.substring (k, j + 1);//start index includes, end index does not include update longest palindrome -k--; -J + +; + Continue; - } + Break;//Both sides do not satisfy the direct exit A } at}//if - if(i-1 >= 0 && i + 1 < s.length () && s.charat (i-1) = = S.charat (i + 1)) {//Take I as the center - intj = i + 1; - intK = I-1; - //i = i-1; //extend both sides of the center - while(k >= 0 && J <s.length ()) { in if(S.charat (k) = =S.charat (j)) { - if((j-k + 1) >result.length ()) toresult = S.substring (k, j + 1); +k--; -J + +; the Continue; *}// while $ Break;Panax Notoginseng } - } the } + A returnresult; the } + } -}
Longest palindromic Substring