forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_5.java
47 lines (40 loc) · 1.23 KB
/
_5.java
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
38
39
40
41
42
43
44
45
46
47
package com.fishercoder.solutions;
/**
* 5. Longest Palindromic Substring
*
* Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
*/
public class _5 {
public static class Solution1 {
private int low;
private int maxLen;
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2) {
return s;
}
for (int i = 0; i < len - 1; i++) {
extendPalindrome(s, i, i); // assume odd length, try to extend Palindrome as possible
extendPalindrome(s, i, i + 1); // assume even length.
}
return s.substring(low, low + maxLen);
}
private void extendPalindrome(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
if (maxLen < right - left - 1) {
low = left + 1;
maxLen = right - left - 1;
}
}
}
}