JAVA编写一个函数longestPalindrome(),找到非空字符串s中最长回文子串
时间: 2024-05-09 07:20:15 浏览: 7
以下是JAVA编写的longestPalindrome()函数代码:
```
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
```
该函数使用中心扩展算法,首先判断字符串是否为空,然后遍历字符串中的每个字符,分别以当前字符为中心向左右扩展,找到最长回文子串的长度。在遍历过程中更新最长回文子串的起始位置和结束位置,最后返回最长回文子串。expandAroundCenter()函数用于以当前字符为中心向左右扩展并返回最长回文子串的长度。