LeetCode Q5 Longest Palindromic Substring

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
class Solution
{
public String longestPalindrome(String s)
{
if(s == null || s.length() < 1) return "";
int start = 0, end = 0;
for(int i = 0; i < s.length(); i++)
{
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if(len > end - start)
{
start = i - (len-1)/2;
end = i + len/2;
}
}
return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right)
{
int L = left, R = right;
while(L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R))
{
L--;
R++;
}
return R - L - 1;
}
}