1. fun longestPalindrome(s: String): String {
    2. if (s.length < 2) return s
    3. var strStart = 0 // 最长回文子串起始位置
    4. var strEnd = 0 // 最长回文子串终止位置
    5. var startIndex = 0 // 当前子串起始索引
    6. var endIndex = 0 // 当前子串终止索引
    7. var nowIndex = 0 // 记录探索的位置
    8. // 检查回文子串长度
    9. fun checkLength() {
    10. while (0 <= startIndex && endIndex < s.length && s[startIndex] == s[endIndex]) {
    11. if ((strEnd-strStart) < (endIndex - startIndex)) {
    12. strEnd = endIndex
    13. strStart = startIndex
    14. }
    15. startIndex--
    16. endIndex++
    17. }
    18. }
    19. while (nowIndex < s.length) {
    20. // 奇数个回文字符
    21. startIndex = nowIndex - 1
    22. endIndex = nowIndex + 1
    23. checkLength()
    24. // 偶数个回文字符
    25. startIndex = nowIndex
    26. endIndex = nowIndex + 1
    27. checkLength()
    28. nowIndex++
    29. }
    30. return s.substring(strStart, strEnd+1)
    31. }