参考点击打开链接
关键是第一个for循环,找到每个字符串的中心位置,然后以此中心位置向两边出发,
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
if (s.length() == 1) {
return s;
}
String maxStr = "";
for (int i = 0; i < 2*s.length() - 1; i++) {
int left = i / 2;
int right = i / 2;
if (i % 2 == 1) {
<span style="white-space:pre"> </span>//保证奇偶两种情况都能照顾到
right++;
}
String str = helper(s, left, right);
if (str.length() > maxStr.length()) {
maxStr = str;
}
}
return maxStr;
}
private String helper(String s, int left, int right) {
while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}
}
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.