给你一个字符串 s,找到 s 中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
+ (NSString *)hy_longestPalindrome:(NSString *)s {
NSInteger length = s.length;
if (length < 2) {
return s;
}
NSInteger start = 0;
NSInteger maxLength = 1;
for (NSInteger i = 0; i < length; i++) {
// 寻找以i为中心的奇数长度的回文串
NSInteger left = i - 1;
NSInteger right = i + 1;
while (left >= 0 && right < length && [s characterAtIndex:left] == [s characterAtIndex:right]) {
left--;
right++;
}
NSInteger oddLength = right - left - 1;
// 寻找以i和i+1为中心的偶数长度的回文串
left = i;
right = i + 1;
while (left >= 0 && right < length && [s characterAtIndex:left] == [s characterAtIndex:right]) {
left--;
right++;
}
NSInteger evenLength = right - left - 1;
// 取最长的回文串
NSInteger currentMaxLength = MAX(oddLength, evenLength);
if (currentMaxLength > maxLength) {
maxLength = currentMaxLength;
start = i - (maxLength - 1) / 2;
}
}
NSRange range = NSMakeRange(start, maxLength);
NSString *result = [s substringWithRange:range];
return result;
}
longestPalindrome: 是该方法的名称,输入参数为一个 NSString 对象,输出也是一个 NSString 对象。
首先判断字符串长度是否小于 2,如果是,则直接返回原字符串。
初始化最长回文子串的起始位置为 0,长度为 1。
遍历字符串中每个字符,以该字符为中心分别向左右扩展,寻找奇数长度和偶数长度的回文串,并记录其长度。
取两种回文串中长度较大的一个,判断是否比当前最长回文子串的长度更长,如果是,则更新最长回文子串的起始位置和长度。
最后利用 substringWithRange 函数获取最长回文子串,并返回。