Swift 4.2
class Solution {
func longestPalindrome(_ s: String) -> String {
if s.count <= 1 {
return s
}
var characters = Array(s)
var temp: (startIndex: Int, length: Int ) = (0, 1)
for index in 0..<characters.count {
var i = index
var j = index + 1
var m = index + 2
var k = 0
var total = 0
while i >= 0 && j < characters.count && characters[i] == characters[j] {
i -= 1
j += 1
k += 1
}
var n = index
var l = 0
if m < characters.count {
while n >= 0 && m < characters.count && characters[n] == characters[m] {
n -= 1
m += 1
l += 1
}
}
total = k > l ? 2 * k : 2 * l + 1
if temp.length < total {
temp.length = total
temp.startIndex = index + 1 - total / 2
}
}
return String(characters[temp.startIndex...temp.length - 1 + temp.startIndex])
}
}
网友评论