给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。示例 2:
输入:s = "cbbd"
输出:"bb"LeetCode:https://leetcode.cn/problems/longest-palindromic-substring
class Solution {
func longestPalindrome(_ s: String) -> String {
// swift字符串使用下标不方便使用,性能也很差
let s = Array(s)
// 最长回文的起止下标
var res = (0, 0)
// 分别枚举每个字符为中心的回文
for i in 0 ..< s.count - 1 {
// 以i为中心的最长回文:abcba
let p1 = palindrome(i, i)
if p1.1 - p1.0 > res.1 - res.0 {
res = p1
}
// 以i和i+1为中心的最长回文:abccba
let p2 = palindrome(i, i+1)
if p2.1 - p2.0 > res.1 - res.0 {
res = p2
}
}
// 向两侧查找以i,j为中点的回文,当i==j时为奇数回文串
func palindrome(_ i: Int, _ j: Int) -> (Int, Int) {
// i,j字符不相等说明不是回文串,最长一个字符
if s[i] != s[j] {
return (i, i)
}
// i,j同时向两侧查找到一个最长回文串
var i = i, j = j
while i >= 0, j < s.count, s[i] == s[j] {
i -= 1
j += 1
}
// i,j字符不等了,需要两端各减1才是回文的区间
return (i + 1, j - 1)
}
// 将区间转为字符串
return String(s[res.0 ... res.1])
}
}
image.png
网友评论