1- // Solution1: T: O(n^2) S: O(1)
1+ // Solution1: 衍生法,少有的,暴力比 dp 更好 T: O(n^2) S: O(1)
22class Solution {
33 public String longestPalindrome (String s ) {
4- int len = s .length ();
5- int max = 0 ;
6- int idx = 0 ;
7- for (int i = 0 ; i < len ; i ++) {
8- int len1 = extend (s , i , i ); // assume odd length, try to extend palindrome as possible
9- int len2 = extend (s ,i , i +1 ); // assume enven length
10- if (Math .max (len1 , len2 ) > max ) {
11- // Update
12- max = Math .max (len1 , len2 );
13- idx = len1 > len2 ? (i - len1 /2 ) : (i - len2 /2 + 1 );
14- }
4+ if (s == null || s .length () == 0 ) return s ;
5+ int n = s .length ();
6+ String res = "" ;
7+ for (int i = 0 ; i < n ; i ++) {
8+ String r1 = findPalindrome (s , i , i );
9+ String r2 = findPalindrome (s , i , i +1 );
10+ if (r1 .length () > res .length ()) res = r1 ;
11+ if (r2 .length () > res .length ()) res = r2 ;
1512 }
16- return s .substring (idx , idx + max );
13+ return res ;
14+
1715 }
1816
19- private int extend (String s , int i , int j ) {
20- int len = s .length ();
21- for (; i >= 0 && j < len ; i --, j ++) {
22- if (s .charAt (i ) != s .charAt (j )) break ;
17+ public String findPalindrome (String str , int l , int r ) {
18+ while (l >= 0 && r < str .length ()) {
19+ if (str .charAt (l ) == str .charAt (r )) {
20+ l --;
21+ r ++;
22+ }
23+ else {
24+ break ;
25+ }
2326 }
24- return j - i + 1 - 2 ; // Current 2 unmatched chars
27+ return str . substring ( l + 1 , r );
2528 }
2629}
2730
28- // Solution2: Dynamic Programming T: O(n^2) S: O(n^2)
31+ // Solution: dp T: O(n^2) S: O(n^2)
2932class Solution {
3033 public String longestPalindrome (String s ) {
31- int len = s .length ();
32- boolean [][] dp = new boolean [len ][len ];
34+ if (s == null || s .length () == 0 ) return s ;
35+ int n = s .length ();
36+ boolean [][] dp = new boolean [n ][n ];
37+ // base case
38+ for (int i = 0 ; i < n ; i ++) {
39+ dp [i ][i ] = true ;
40+ }
41+ // 推导
3342 String res = "" ;
34- for (int i = len - 1 ; i >= 0 ; i --) {
35- for (int j = i ; j < len ; j ++) {
36- if (j - i <= 2 ) dp [i ][j ] = (s .charAt (i ) == s .charAt (j ));
37- else dp [i ][j ] = (s .charAt (i ) == s .charAt (j )) && dp [i +1 ][j -1 ];
38- if (dp [i ][j ] && res .length () < j - i + 1 ) {
39- res = s .substring (i , j + 1 );
43+ int maxLen = 0 ;
44+ for (int i = n -1 ; i >= 0 ; i --) {
45+ for (int j = i +1 ; j < n ; j ++) {
46+ if (j - i == 1 ) {
47+ dp [i ][j ] = (s .charAt (i ) == s .charAt (j ));
48+ }
49+ else {
50+ dp [i ][j ] = (dp [i +1 ][j -1 ] && (s .charAt (i ) == s .charAt (j )));
51+ }
52+ if (dp [i ][j ] && j - i + 1 > maxLen ) {
53+ maxLen = j - i + 1 ;
54+ res = s .substring (i , j +1 );
4055 }
4156 }
4257 }
43- return res ;
58+ if (maxLen != 0 ) return res ;
59+ return String .valueOf (s .charAt (0 ));
4460 }
4561}
0 commit comments