[Link] https://leetcode.com/problems/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
class Solution {
public String longestPalindrome(String s) {
int max = 0, startIdx = 0, endIdx = 0, len = s.length();
for(int i = 0; i < s.length(); i++) {
int start = i, end1 = i, end2 = i+1, end;
boolean continue1 = true, continue2 = true;
while(start >= 0 && (continue1 || continue2)) {
if(continue1 == true) {
if(end1 < len && s.charAt(start) == s.charAt(end1)) end1++;
else continue1 = false;
}
if(continue2 == true) {
if(end2 < len && s.charAt(start) == s.charAt(end2)) end2++;
else continue2 = false;
}
if(continue1 || continue2) start--;
}
// System.out.println(i + " , " + start + " , " + end1 + " , " + end2);
// end1--;
// end2--;
end = end1 > end2 ? end1 : end2;
if(max < end - ++start + 1) {
max = end - start + 1;
startIdx = start;
endIdx = end -1;
}
}
// System.out.println(startIdx + " , " + endIdx + " max: " + max);
return s.substring(startIdx, endIdx + 1);
}
}