File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments