Skip to content

Commit b7c4922

Browse files
committed
#266 Longest Palindromic Substring
1 parent 58a1007 commit b7c4922

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
# Time Complexity: O(n^2)
3+
# Spcae Complexity: O(1)
4+
*/
5+
class Solution {
6+
public String longestPalindrome(String s) {
7+
String ans = "";
8+
for (int i = 0; i < s.length(); i++) {
9+
int l = i;
10+
int r = i;
11+
12+
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
13+
if (r - l + 1 > ans.length()) ans = s.substring(l, r + 1);
14+
l--;
15+
r++;
16+
}
17+
18+
l = i;
19+
r = i + 1;
20+
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
21+
if (r - l + 1 > ans.length()) ans = s.substring(l, r + 1);
22+
l--;
23+
r++;
24+
}
25+
}
26+
27+
return ans;
28+
}
29+
}

0 commit comments

Comments
 (0)