题目描述:
给定一个字符串 s
,找到 s
中最长的回文子串。你可以假设 s
的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
解题思路:
直接暴力解决,先将字符串转换成数组,在一个个遍历,寻找与给出字符相同的字符位置,再左右同时遍历对比,符合情况则记录maxLength值,再次循环对比,知直到maxLength最大值,返回符合的字符串
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
char[] chars = s.toCharArray();
int num = chars.length - 1;
int maxLength = 0;
int left = 0;
int right = 0;
for (int i = 0; i < chars.length - maxLength; ) {
char ch = chars[i];
int pos = s.lastIndexOf(ch, num);
if (i == pos || pos - i < maxLength) {
i++;
num = chars.length - 1;
continue;
}
int posRec = pos;
pos--;
boolean success = true;
for (int j = i + 1; j < pos; j++, pos--) {
if (chars[j] != chars[pos]) {
success = false;
break;
}
}
if (success) {
maxLength = posRec - i;
left = i;
right = posRec;
}
num = posRec - 1;
}
return s.substring(left, right + 1);
}
}