1 public class Solution { 2 public String longestPalindrome(String s) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int n = s.length(); 6 if (n == 0) return ""; 7 String longest = String.valueOf(s.charAt(0)); // a single char itself is a palindrome 8 for (int i = 0; i < n-1; i++) { 9 String p1 = expandAroundCenter(s, i, i); 10 if (p1.length() > longest.length()) 11 longest = p1; 12 13 String p2 = expandAroundCenter(s, i, i+1); 14 if (p2.length() > longest.length()) 15 longest = p2; 16 } 17 return longest; 18 } 19 20 private String expandAroundCenter(String s, int c1, int c2) { 21 int l = c1, r = c2; 22 int n = s.length(); 23 while (l >= 0 && r <= n-1 && s.charAt(l) == s.charAt(r)) { 24 l--; 25 r++; 26 } 27 return s.substring(l+1, r); 28 } 29 30 }
O(n2) level 1
Manacher’s algorithm O(n) level 5