# LeetCode 刷题笔记 - 5. 最长回文子串

## 示例

``````1：

``````2：

swift

## 解析：

``````class Solution {
func longestPalindrome(_ s: String) -> String {
if s.count == 0 || s == "" {
return ""
}
var longestString = ""
let stringArray = Array(s)
var insertArray = Array<Character>()
for index in 0...stringArray.count * 2 {
if index % 2 == 0 {
insertArray.append(Character("#"))
} else {
insertArray.append(stringArray[(index - 1) / 2])
}
}
let arrayLength = insertArray.count
for index in 1...insertArray.count - 2 {
let value = insertArray[index]
let maxOffset = index <= arrayLength - 1 - index ? index : arrayLength - 1 - index
var tempString = String(value)
if tempString == "#" {
tempString = ""
}
for offset in 1...maxOffset {
let offsetLeftValue = insertArray[index - offset]
let offsetRightValue = insertArray[index + offset]
if offsetLeftValue != offsetRightValue {
break
} else {
if offsetLeftValue != "#" {
tempString = String(offsetLeftValue) + tempString + String(offsetRightValue)
}
}
}
if longestString.count < tempString.count {
longestString = tempString
}
}
return longestString
}
}