fun longestPalindrome(s: String): String { if (s.length < 2) return s var strStart = 0 // 最长回文子串起始位置 var strEnd = 0 // 最长回文子串终止位置 var startIndex = 0 // 当前子串起始索引 var endIndex = 0 // 当前子串终止索引 var nowIndex = 0 // 记录探索的位置 // 检查回文子串长度 fun checkLength() { while (0 <= startIndex && endIndex < s.length && s[startIndex] == s[endIndex]) { if ((strEnd-strStart) < (endIndex - startIndex)) { strEnd = endIndex strStart = startIndex } startIndex-- endIndex++ } } while (nowIndex < s.length) { // 奇数个回文字符 startIndex = nowIndex - 1 endIndex = nowIndex + 1 checkLength() // 偶数个回文字符 startIndex = nowIndex endIndex = nowIndex + 1 checkLength() nowIndex++ } return s.substring(strStart, strEnd+1)}