Skip to content

Latest commit

 

History

History
37 lines (34 loc) · 867 Bytes

林浩特-20180721.md

File metadata and controls

37 lines (34 loc) · 867 Bytes

【leetcode 算法题】

https://leetcode.com/problems/longest-palindromic-substring/description/

func expandAroundCenter(s string, left, right int) string {
    if left < 0 || right > len(s) - 1 || s[left] != s[right] {
        return ""
    }
    L := left
    R := right
    for L >= 0 && R < len(s) && s[L] == s[R] {
        L--
        R++
    }
    // log.Printf("expandAroundCenter[%s][%d, %d]=[%d, %d]", s, left, right, L+1, R)
    return s[L+1:R]
}

func longestPalindrome(s string) string {
    if len(s) < 2 {
        return s
    }
    maxStr := ""
    for i:= 0; i<len(s); i++ {
        sub1 := expandAroundCenter(s, i, i)
        sub2 := expandAroundCenter(s, i, i+1)
        if len(sub1) > len(maxStr) {
            maxStr = sub1
        }
        if len(sub2) > len(maxStr) {
            maxStr = sub2
        }
    }
    return maxStr
}