1. 题目描述
给你一个字符串 s,找到 s 中最长的回文子串。
2. 示例
3. 提示
- 1 <= s.length <= 1000
- s 仅由数字和英文字母组成(大小写)
4. solution
- 最外层循环从索引为1 到 最大索引;
- 从索引为1开始查找,若左右元素相同,再继续向两侧扩展(但只考虑这种情况不适用于类似 aaaa 的例子),求得一个最大长度;
- 为了处理上述情况(以 aaaa 为例),添加了下面的代码,从索引为2开始,若与左侧相等,则从索引 1 与 2 同时往两侧扩展(但只考虑这种情况不适用于处理类似 aaa 的例子),求得一个最大长度。
- 取两种情况的最大长度,并记录下索引位置。
- 根据记录的索引位置输出即可。
class Solution {
public String longestPalindrome(String s) {
// 1.特殊情况:长度为一的字符串,直接返回
if(s.length() == 1){
return s;
}
// 2.一般情况:循环查找
int max = 1,start = 0,end = 0;
char[] cStr = s.toCharArray();// 转化为字符数组
for (int i = 1; i < cStr.length; i++) {
int left = i, right = i, count = 1;// 存放当前最大回文子串的始末索引,及长度
while ((left - 1) >= 0 && (right + 1) < cStr.length) {
if (cStr[left - 1] == cStr[right + 1]) {
left -= 1;
right += 1;
count += 2;
} else {
break;
}
}
if(max < count){
start = left;
end = right;
max = count;
}
left = i;right = i;count = 1;// 存放当前最大回文子串的始末索引,及长度
if((left-1)>=0 && (cStr[left]==cStr[left-1])){
left -= 1;
++count;
}
while((left-1)>=0 && (right+1)<cStr.length){
if(cStr[left-1] == cStr[right+1]){
left -= 1;
right += 1;
count += 2;
}else{
break;
}
}
if(max < count){
start = left;
end = right;
max = count;
}
}
// 3.输出索引为 left ~ right 之间的字符组成的字符串
String result = "";
for (int i = start; i <= end; i++) {
result += cStr[i];
}
return result;
}
}
5. 题目来源
力扣