File tree Expand file tree Collapse file tree 1 file changed +9
-12
lines changed Expand file tree Collapse file tree 1 file changed +9
-12
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public String longestPalindrome (String s ) {
3
- if (s == null || s .length () == 0 ) {
4
- return s ;
5
- }
3
+ int len = s .length ();
6
4
7
- int start = 0 , end = 0 , n = s . length () ;
8
- boolean [][] dp = new boolean [ n ][ n ] ;
5
+ boolean [][] dp = new boolean [ len ][ len ] ;
6
+ String result = "" ;
9
7
10
- for (int i = n - 1 ; i >= 0 ; i --) {
11
- for (int j = i ; j < n ; j ++) {
12
- dp [i ][j ] = s .charAt (i ) == s .charAt (j ) && (j - i < 2 || dp [i + 1 ][j - 1 ]);
8
+ for (int i = len - 1 ; i >= 0 ; i --) {
9
+ for (int j = i ; j < len ; j ++) {
10
+ dp [i ][j ] = s .charAt (i ) == s .charAt (j ) && (j - i < 3 || dp [i + 1 ][j - 1 ]);
13
11
14
- if (dp [i ][j ] && j - i > end - start ) {
15
- start = i ;
16
- end = j ;
12
+ if (dp [i ][j ] && j - i + 1 > result .length ()) {
13
+ result = s .substring (i , j + 1 );
17
14
}
18
15
}
19
16
}
20
17
21
- return s . substring ( start , end + 1 ) ;
18
+ return result ;
22
19
}
23
20
}
You can’t perform that action at this time.
0 commit comments