File tree 1 file changed +28
-19
lines changed
src/main/java/com/fibers/algorithm/leetcode/_005
1 file changed +28
-19
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class Solution {
4
4
public String longestPalindrome (String s ) {
5
- int start = 0 ;
6
- int end = 0 ;
5
+ if (s == null || s .length () == 0 ){
6
+ return s ;
7
+ }
8
+
7
9
int len = s .length ();
10
+ boolean [][] dp = new boolean [len ][len ];
11
+ int left = 0 ;
12
+ int right = 0 ;
13
+ int max = 0 ;
8
14
9
- for (int i = 0 ; i < len ; i ++) {
10
- int len1 = expandAroundCenter (s , i , i );
11
- int len2 = expandAroundCenter (s , i , i +1 );
12
- int maxLen = Math .max (len1 , len2 );
13
- if (maxLen > end - start ) {
14
- start = i - (maxLen - 1 ) / 2 ;
15
- end = i + maxLen / 2 ;
16
- }
17
- }
15
+ for (int i = 0 ; i <len ; i ++){
16
+ dp [i ][i ] = true ;
17
+ for (int j = 0 ; j <i ; j ++){
18
+ // dp[j][i] = (s.charAt(i) == s.charAt(j) && ( i-j < 2 || dp[j+1][i-1]));
18
19
19
- return s .substring (start , end + 1 );
20
- }
20
+ if (s .charAt (i ) == s .charAt (j )){
21
+ if (i -j < 2 ){
22
+ dp [j ][i ] = true ;
23
+ }else {
24
+ dp [j ][i ] = dp [j +1 ][i -1 ];
25
+ }
26
+ }else {
27
+ dp [j ][i ] = false ;
28
+ }
21
29
22
- private int expandAroundCenter (String s , int left , int right ) {
23
- int len = s .length ();
24
- while (left >= 0 && right < len && s .charAt (left ) == s .charAt (right )) {
25
- left --;
26
- right ++;
30
+ if (dp [j ][i ] && i -j + 1 > max ){
31
+ max = i -j +1 ;
32
+ left = j ;
33
+ right = i ;
34
+ }
35
+ }
27
36
}
28
- return right - left - 1 ;
37
+ return s . substring ( left , right + 1 ) ;
29
38
}
30
39
}
You can’t perform that action at this time.
0 commit comments