5. Longest Palindromic Substring

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
char[] ch = s.toCharArray();
int maxLength = 0;
String result = "";

for (int i = 0; i < len; i++) {
// odd length (central is i)
int maxSubLength = Math.min(i, len - 1 - i);
for (int j = 0; j <= maxSubLength; j++) {
if (ch[i + j] == ch[i - j]) {
if (2 * j + 1 > maxLength) {
maxLength = 2 * j + 1;
result = s.substring(i - j, i + j + 1);
}
} else {
break;
}
}

// even length (central between i and i+1)
if (i + 1 < len && ch[i] == ch[i + 1]) {
int j = 0;
while (i - j >= 0 && i + 1 + j < len && ch[i - j] == ch[i + 1 + j]) {
if (2 * (j + 1) > maxLength) {
maxLength = 2 * (j + 1);
result = s.substring(i - j, i + 1 + j + 1);
}
j++;
}
}
}

return result;
}
}

Remarks:

  1. handle two conditions: odd length and even length
  2. be careful with the boundary