-
Notifications
You must be signed in to change notification settings - Fork 20
/
LongestPalindromicSubstring.java
57 lines (52 loc) · 1.56 KB
/
LongestPalindromicSubstring.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
48
49
50
51
52
53
54
55
56
57
/**
* Given a string s, find the longest palindromic substring in s.
* You may assume that the maximum length of s is 1000.
* <p>
* Example:
* <p>
* Input: "babad"
* <p>
* Output: "bab"
* <p>
* Note: "aba" is also a valid answer.
* Example:
* <p>
* Input: "cbbd"
* <p>
* Output: "bb"
* <p>
* Accepted.
*/
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if (s == null || s.length() <= 1) {
return s;
}
int maxLength = 0, startIndex = 0;
for (int index = 0; index < s.length(); index++) {
int leftIndex = index;
int rightIndex = index;
while (leftIndex >= 0 && rightIndex < s.length() && s.charAt(leftIndex) == s.charAt(rightIndex)) {
int current = rightIndex - leftIndex + 1;
if (current > maxLength) {
maxLength = current;
startIndex = leftIndex;
}
leftIndex--;
rightIndex++;
}
leftIndex = index;
rightIndex = index + 1;
while (leftIndex >= 0 && rightIndex < s.length() && s.charAt(leftIndex) == s.charAt(rightIndex)) {
int current = rightIndex - leftIndex + 1;
if (current > maxLength) {
maxLength = current;
startIndex = leftIndex;
}
leftIndex--;
rightIndex++;
}
}
return s.substring(startIndex, maxLength + startIndex);
}
}