Skip to content

Commit b71635d

Browse files
committed
Updated longest palindromic substring
1 parent f6f50d0 commit b71635d

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

Medium/LongestPalindromicSubstring.java

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
class LongestPalindromicSubstring {
99

1010
public static void main(String[] args) {
11-
11+
LongestPalindromicSubstring l = new LongestPalindromicSubstring();
12+
String s = "abba";
13+
System.out.println(l.longestPalindrome(s));
1214
}
1315

1416
/**
@@ -18,23 +20,28 @@ public static void main(String[] args) {
1820
public String longestPalindrome(String s) {
1921
if (s == null || s.length() == 0) return "";
2022

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 = "";
2426

25-
for (int i = 1; i <= 2 * length - 1; i++) {
27+
for (int i = 1; i <= 2 * len - 1; i++) { // skip two #s
2628
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++;
2830
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);
3133
max = count;
3234
}
3335
}
3436

35-
return result;
37+
return res;
3638
}
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+
*/
3845
private char get(String s, int i) {
3946
if (i % 2 == 0) return '#';
4047
else return s.charAt(i / 2);
@@ -46,7 +53,7 @@ private char get(String s, int i) {
4653
* http://www.felix021.com/blog/read.php?2040
4754
* http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
4855
*/
49-
public String longestPalindrome(String s) {
56+
public String longestPalindromeB(String s) {
5057
String t = preProcess(s);
5158
int n = t.length();
5259
int[] p = new int[n];
@@ -89,7 +96,7 @@ private String preProcess(String s) {
8996
* Expand from center character and center of two chars
9097
* Update result according to the returned length
9198
*/
92-
public String longestPalindromeB(String s) {
99+
public String longestPalindromeC(String s) {
93100
if (s == null || s.length() == 0) return "";
94101
String longest = s.substring(0, 1);
95102
int len = s.length();
@@ -115,4 +122,4 @@ private String expandAroundCenter(String s, int i, int j) {
115122
}
116123
return s.substring(l + 1, r); // note the range is from l + 1 to r - 1
117124
}
118-
}
125+
}

0 commit comments

Comments
 (0)