Skip to content

Commit 1f134cd

Browse files
committed
Longest Palindromic Substring
1 parent 06d77e2 commit 1f134cd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// TC: O(n^2)
2+
// for loop & nested while loop => total O(n^2)
3+
// SC: O(1)
4+
// uses only constant space => O(1)
5+
class Solution {
6+
public String longestPalindrome(String s) {
7+
int right = 0;
8+
int left = 0;
9+
10+
for (int i = 0; i < s.length(); i++) {
11+
int even = pad(s, i, i);
12+
int odd = pad(s, i, i+1);
13+
int max = Math.max(even, odd);
14+
15+
if (max > (right - left)) {
16+
right = i + (max + 1) / 2;
17+
left = i - max / 2;
18+
}
19+
}
20+
21+
return s.substring(left, right+1);
22+
}
23+
24+
private int pad(String s, int start, int end) {
25+
while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
26+
start -= 1;
27+
end += 1;
28+
}
29+
return start - end;
30+
}
31+
}

0 commit comments

Comments
 (0)