8
8
class LongestPalindromicSubstring {
9
9
10
10
public static void main (String [] args ) {
11
-
11
+ LongestPalindromicSubstring l = new LongestPalindromicSubstring ();
12
+ String s = "abba" ;
13
+ System .out .println (l .longestPalindrome (s ));
12
14
}
13
15
14
16
/**
@@ -18,23 +20,28 @@ public static void main(String[] args) {
18
20
public String longestPalindrome (String s ) {
19
21
if (s == null || s .length () == 0 ) return "" ;
20
22
21
- int length = s .length ();
22
- int max = 0 ;
23
- String result = "" ;
23
+ int len = s .length ();
24
+ int max = 0 ; // max length
25
+ String res = "" ;
24
26
25
- for (int i = 1 ; i <= 2 * length - 1 ; i ++) {
27
+ for (int i = 1 ; i <= 2 * len - 1 ; i ++) { // skip two #s
26
28
int count = 1 ;
27
- while (i - count >= 0 && i + count <= 2 * length && get (s , i - count ) == get (s , i + count )) count ++;
29
+ while (i - count >= 0 && i + count <= 2 * len && get (s , i - count ) == get (s , i + count )) count ++;
28
30
count --; // there will be one extra count for the outbound #
29
- if (count > max ) {
30
- result = s .substring ((i - count ) / 2 , (i + count ) / 2 );
31
+ if (count > max ) { // update max and result when longer is found
32
+ res = s .substring ((i - count ) / 2 , (i + count ) / 2 );
31
33
max = count ;
32
34
}
33
35
}
34
36
35
- return result ;
37
+ return res ;
36
38
}
37
-
39
+
40
+ /**
41
+ * Insert char to the original input string
42
+ * If the index is even, return #
43
+ * If the index is odd, return char in the original string
44
+ */
38
45
private char get (String s , int i ) {
39
46
if (i % 2 == 0 ) return '#' ;
40
47
else return s .charAt (i / 2 );
@@ -46,7 +53,7 @@ private char get(String s, int i) {
46
53
* http://www.felix021.com/blog/read.php?2040
47
54
* http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
48
55
*/
49
- public String longestPalindrome (String s ) {
56
+ public String longestPalindromeB (String s ) {
50
57
String t = preProcess (s );
51
58
int n = t .length ();
52
59
int [] p = new int [n ];
@@ -89,7 +96,7 @@ private String preProcess(String s) {
89
96
* Expand from center character and center of two chars
90
97
* Update result according to the returned length
91
98
*/
92
- public String longestPalindromeB (String s ) {
99
+ public String longestPalindromeC (String s ) {
93
100
if (s == null || s .length () == 0 ) return "" ;
94
101
String longest = s .substring (0 , 1 );
95
102
int len = s .length ();
@@ -115,4 +122,4 @@ private String expandAroundCenter(String s, int i, int j) {
115
122
}
116
123
return s .substring (l + 1 , r ); // note the range is from l + 1 to r - 1
117
124
}
118
- }
125
+ }
0 commit comments