Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Example
Given the string = "abcdzdcab", return "cdxdc".
思路 1
因为有String有偶数奇数长度之分,所以不能直接对String基于每个字母进行判断。
需要对其进行插板操作,比如 # a # b # b # c # 或者 # a # b # c# 这样填充之后,奇偶长度的字符串都变成了偶数长度的字符串(从0开始)
- 从左到右依次每个字母进行判断
- 从每个字母左右延伸,知道判断到其为回文则停止,得到该subString和回文长度
- 判断是否回文,判断
String(i - count) == String (i + count)
。 如果 i - count为偶数则代表,其为#, 若为奇数则其为String(i-count/2)的字母
- 判断是否回文,判断
- 如果得到了更长的substring回文长度,更新该长度和substring
public class Solution {
/*
* @param s: input string
* @return: the longest palindromic substring
*/
public String longestPalindrome(String s) {
// write your code here
// 思路: 1. 从左到右挨个字母判断
// 2. 从每个字母左右延伸,直到判断其非回文则停止,得到该substring的回文长度
if (s == null || s.length() <= 1) {
return s;
}
int len = s.length();
int count = 0;
int maxLen = 0;
String result = null;
for (int i = 0; i < 2 * len - 1; i++) {
count = 1;
while (i - count >= 0 && i + count <= 2 * len && getChar(i - count, s) == getChar(i + count, s)) {
count++;
// System.out.print(i);
// System.out.print(count);
// System.out.print(getChar(i - count, s));
// System.out.print(getChar(i + count, s));
}
count--;
if (count > maxLen) {
maxLen = count;
result = s.substring((i - count) / 2, (i + count) / 2);
count = 0;
}
}
return result;
}
private Character getChar(int i, String s) {
if (i % 2 == 0) {
return '#';
} else {
return s.charAt(i / 2);
}
}
}
Solution 2
class Solution {
public String longestPalindrome(String s) {
// corner case
if (s == null || s.length() == 0 || s.length() == 1)
return s;
int[] max = new int[2];
for (int i = 0; i + 1 < s.length(); ++ i) {
int[] range = getLongestPalindrome(s, i, i);
if (range[1] - range[0] > max[1] - max[0]) {
max = range;
}
range = getLongestPalindrome(s, i, i + 1);
if (range[1] - range[0] > max[1] - max[0]) {
max = range;
}
}
return s.substring(max[0], max[1] + 1);
}
private int[] getLongestPalindrome(String s, int left, int right) {
int[] res = new int[2];
int last = s.length() - 1;
while (left >= 0 && right <= last && s.charAt(left) == s.charAt(right)) {
-- left;
++ right;
}
res[0] = left + 1;
res[1] = right - 1;
return res;
}
}