File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
leetcode/medium/5. Longest Palindromic Substring Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ public static void main (String [] args ) {
4
+ String s = "abba" ;
5
+ System .out .println (longestPalindromeOn2 (s ));
6
+ }
7
+
8
+ public static String longestPalindromeOn2 (String s ) {
9
+
10
+ if (s == null || s .length () < 1 ) return "" ;
11
+
12
+ int start = 0 ;
13
+ int end = 0 ;
14
+
15
+ for (int i = 0 ; i < s .length (); i ++){
16
+ int lenOdd = expandFromMiddle (s , i , i );
17
+ int lenEven = expandFromMiddle (s , i , i +1 );
18
+ int lenMax = Math .max (lenOdd , lenEven );
19
+ if (lenMax > end - start ){
20
+ start = i - ((lenMax - 1 )/ 2 );
21
+ end = i + (lenMax /2 );
22
+ }
23
+ }
24
+
25
+ return s .substring (start , end +1 );
26
+
27
+ }
28
+
29
+ public static int expandFromMiddle (String s , int left , int right ){
30
+
31
+ if (s == null || left > right ) return 0 ;
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 ;
39
+
40
+ }
41
+ }
Original file line number Diff line number Diff line change
1
+ Given a string s, return the longest palindromic substring in s.
2
+
3
+
4
+
5
+ Example 1:
6
+
7
+ Input: s = "babad"
8
+ Output: "bab"
9
+ Explanation: "aba" is also a valid answer.
10
+ Example 2:
11
+
12
+ Input: s = "cbbd"
13
+ Output: "bb"
14
+
15
+
16
+ Constraints:
17
+
18
+ 1 <= s.length <= 1000
19
+ s consist of only digits and English letters.
20
+
21
+ Hint:
22
+ There are three ways to solve it
23
+ 1. O(n3) -> for each of all the substring see if its palindrome or not
24
+ 2. O(n2) -> Expand From middle Approach
25
+ 3. O(n) -> Manacher's Algorithm -> Very hard
You can’t perform that action at this time.
0 commit comments