Skip to content

Commit 174fec9

Browse files
committed
feat: longest-palindromic-substring
1 parent 0307571 commit 174fec9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/longest-palindromic-substring/">week15-3. longest-palindromic-substring</a>
3+
* <li>Description: Given a string s, return the longest palindromic substring in s</li>
4+
* <li>Topics: Two Pointers, String, Dynamic Programming</li>
5+
* <li>Time Complexity: O(N), Runtime 15ms </li>
6+
* <li>Space Complexity: O(N), Memory 42.13MB</li>
7+
*/
8+
9+
class Solution {
10+
public String longestPalindrome(String s) {
11+
int start = 0;
12+
int maxLength = 1;
13+
14+
for (int i = 0; i < s.length(); i++) {
15+
int len1 = findPalindrome(s, i, i);
16+
int len2 = findPalindrome(s, i, i + 1);
17+
18+
int len = Math.max(len1, len2);
19+
if (len > maxLength) {
20+
maxLength = len;
21+
start = i - (len - 1) / 2;
22+
}
23+
}
24+
25+
return s.substring(start, start + maxLength);
26+
}
27+
28+
public int findPalindrome(String s, int left, int right) {
29+
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
30+
left--;
31+
right++;
32+
}
33+
34+
return right - left - 1;
35+
}
36+
}

0 commit comments

Comments
 (0)