forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_5.java
99 lines (89 loc) · 3.04 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.fishercoder.solutions;
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;
}
}
}
public static class Solution2 {
/**
* Same sliding window idea, but without using global variables.
* Credit: https://leetcode.com/problems/longest-palindromic-substring/solution/
*/
public String longestPalindrome(String s) {
int start = 0;
int end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expand(s, i, i);
int len2 = expand(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 expand(String s, int left, int right) {
int l = left;
int r = right;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
return r - l - 1;
}
}
public static class Solution3 {
/**
* My own implementation using the same idea.
*/
public String longestPalindrome(String s) {
String ans = "";
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
int[] pair = expand(s, i, i);
if (pair[1] - pair[0] + 1 > maxLen) {
maxLen = pair[1] - pair[0] + 1;
ans = s.substring(pair[0], pair[1] + 1);
}
pair = expand(s, i, i + 1);
if (pair[1] - pair[0] + 1 > maxLen) {
maxLen = pair[1] - pair[0] + 1;
ans = s.substring(pair[0], pair[1] + 1);
}
}
return ans;
}
private int[] expand(String s, int l, int r) {
int[] pair = new int[2];
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
pair[0] = l;
pair[1] = r;
l--;
r++;
}
return pair;
}
}
}