LeetCode 5.最长回文子串
我能理解的最简单的方法:中心扩展法
遍历字符串,以每个字符为中心向两边扩展,同时以两个字符为中心向两边扩展,更新每次扩展后的最大长度。最大回文子串的起始位置=中心位置-(最大回文子串长度 - 1)/ 2,末尾位置=中心位置+最大回文子串长度 / 2,最后返回从起始位置到末尾位置的字符串即可。
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
int start = 0;
int end = 0;
for(int i = 0; i < s.length(); i++) {
int len1 = expend(s, i, i);
int len2 = expend(s, i, i + 1);
int len = Math.max(len1, len2);
if(len > end - start + 1) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
public int expend(String s, int left, int right) {
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
时间复杂度O(n^2)
空间复杂度O(1)