Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
题目:给定一个字符串s,返回s中最长的回文体子串。假设输入字符串的最大长度是1000。
回文体的对称特性:如果字符串s是回文体,则在对称中心左右两侧的字符中,到对称中心距离相同的字符一定相同。假设回文体s的长度是N,如果N是奇数则对称中心是index=(N-1)/2的字符,如果N是偶数则对称中心是index=N/2-1和index=N/2这两个字符中间的虚拟位置。
实现思路:题目让我们返回的是最长回文体子串,那么实现过程中需要求出这个子串的起点与终点位置。因此,遍历每个字符,用相反方向运动的两个指针寻找以当前位置=i的字符作为对称中心的最长回文体子串(从中心向两边扩展),然后更新最终结果的起点和终点位置。具体来说,
- 对当前位置i,由于不知道回文体长度是奇数还是偶数,所以需要考虑全部可能:①假设回文体长度是奇数,则令两个指针的起始位置都是i,求出最大长度为L1;②假设回文体长度是偶数,则令向左移动的指针的初始位置为i、向右移动的指针的初始位置为i+1,求出最大长度为L2;③取L1和L2的最大值,然后求出这个子串的起点和终点位置并更新最终结果。
- 对当前位置i,假设根据上述过程求出的最大长度是L。如果L是奇数,那么这个回文体子串的起点start=i+1/2-L/2、终点end=i-1/2+L/2(因为i-star=end-i且end-start+1=L,表达式中的1/2在实现过程中可以省略)。如果L是偶数,那么这个回文体子串的起点start=i+1-L/2、终点end=i+L/2(因为i-start=end-(i+1)且end-start+1=L)。
class Solution {
public String longestPalindrome(String s) {
if (s == null) return null;
int length = s.length();
if (length == 0) return "";
int start = 0, end = 0;
for (int i = 0; i < length; i++) {
int l1 = expand(s, i, i);
int l2 = expand(s, i, i + 1);
int l = Math.max(l1, l2);
if (l > end - start + 1) {
start = l == l1 ? i - l / 2 : i - l / 2 + 1;
end = i + l / 2;
}
}
return s.substring(start, end + 1);
}
private int expand(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}参考资料:
https://leetcode.com/problems/longest-palindromic-substring/solution/
本文介绍了一种高效算法来找出给定字符串中的最长回文子串。通过中心扩展法,该算法能处理不同长度的回文串,并适用于各种字符串长度,特别是长度达到1000的情况。
602

被折叠的 条评论
为什么被折叠?



