Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
答案:
func longestPalindrome(_ s: String) -> String {
if s.characters.count <= 1 {
return s
}
let charArr = Array(s.characters)
let strLen = s.characters.count
var start = 0
var lenth = 0
var tmpStart = 0
var tmpLen = 0
for j in 0...500 {
if i-j >= 0 && i+1+j < strLen && charArr[i-j] == charArr[i+1+j] {
tmpStart = i - j
tmpLen = (j+1) * 2;
} else {
break;
}
if tmpLen > lenth {
lenth = tmpLen
start = tmpStart
tmpLen = 0
tmpStart = 0
}
for j in 0...500 {
if i-j >= 0 && i+j < strLen && charArr[i-j] == charArr[i+j]{
tmpStart = i - j
tmpLen = j*2 + 1;
} else {
break;
}
if tmpLen > lenth {
lenth = tmpLen
start = tmpStart
tmpLen = 0
tmpStart = 0
}
}
let startIndex = s.index(s.startIndex, offsetBy: start)
let endIndex = s.index(s.startIndex, offsetBy: start + lenth)
let range = startIndex..<endIndex
return s.substring(with: range)
}