Skip to content

Commit b7c9f09

Browse files
authored
Create LongestPalindromicSubstring.java
1 parent fe07bd7 commit b7c9f09

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

LongestPalindromicSubstring.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
3+
//Time: O(n^2), where n is s length
4+
//Space: O(1)
5+
public String longestPalindrome(String s) {
6+
7+
String longestPal = "";
8+
9+
for(int i = 0; i < s.length(); i++) {
10+
int offset1 = expandOffset(s, i, i);
11+
int offset2 = expandOffset(s, i, i + 1);
12+
13+
String subs = "";
14+
15+
int maxOffset = Math.max(offset1, offset2);
16+
17+
if (offset2 > offset1) {
18+
subs = s.substring(i - maxOffset + 1, i + maxOffset + 1);
19+
} else {
20+
subs = s.substring(i - maxOffset, i + maxOffset + 1);
21+
}
22+
23+
if (longestPal.length() < subs.length()) longestPal = subs;
24+
25+
}
26+
27+
return longestPal;
28+
29+
}
30+
31+
private int expandOffset(String s, int left, int right) {
32+
33+
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
34+
left--;
35+
right++;
36+
}
37+
38+
return (right - left - 1) / 2;
39+
40+
}
41+
42+
}

0 commit comments

Comments
 (0)