5. Longest Palindromic Substring#
1class Solution {
2 int left = 0;
3 int maxLength = 0;
4
5 public String longestPalindrome(String s) {
6 if (s.length() < 2) {
7 return s;
8 }
9
10 for (int i = 0; i < s.length() - 1; ++i) {
11 extend(s, i, i);
12 extend(s, i, i + 1);
13 }
14
15 return s.substring(left, left + maxLength);
16 }
17
18 private void extend(String s, int l, int r) {
19 while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
20 l--;
21 r++;
22 }
23
24 if (r - l - 1 > maxLength) {
25 maxLength = r - l - 1;
26 left = l + 1;
27 }
28 }
29}