最长回文子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.Scanner;

public class Main {
public String longestPalindrome(String s) {
int curLen = 0;
int start = -1;
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
if (isPalindrome(array, i - curLen - 1, i)) {
start = i - curLen - 1;
curLen += 2;
} else if (isPalindrome(array, i - curLen, i)) {
start = i - curLen;
curLen += 1;
}
}
return new String(array, start, curLen);
}

private boolean isPalindrome(char[] array, int start, int end) {
if (start < 0) {
return false;
}
while (start < end) {
if (array[start++] != array[end--]) {
return false;
}
}
return true;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.nextLine();
System.out.println(new Main().longestPalindrome(string));
}
}

参考链接

  1. (AC) relatively short and very clear Java solution
  2. LeetCode 5. Longest Palindromic Substring
  3. 最长回文子串——Manacher 算法