NOTE

最长回文子串

最长回文子串:暴力法与中心扩散法。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给你一个字符串 s,找到 s 中最长的回文子串。

2. 思路

  • 暴力法
  • 中心扩散法

3. 实现

3.1. 暴力法

func longestPalindrome(s string) string {
	max := 0
	maxStr := ""
	longestPalindrome2(s, 0, len(s)-1, &max, &maxStr)
	return maxStr
}

func longestPalindrome2(s string, left int, right int, max *int, maxStr *string) {
	if left > right {
		return
	}
	if isHuiWen(s, left, right) {
		current := right - left + 1
		if current > *max {
			*max = current
			*maxStr = s[left : right+1]
		}
	} else {
		longestPalindrome2(s, left+1, right, max, maxStr)
		longestPalindrome2(s, left, right-1, max, maxStr)
	}

}

func isHuiWen(str string, left int, right int) bool {
	for left < right {
		if str[left] != str[right] {
			return false
		}
		left++
		right--
	}
	return true
}

3.2. 中心扩散法


func longestPalindrome(s string) string {
    res := ""
    runes := []rune(s)
    for i, _ := range runes {
        str := spread(runes, i, i)
        if len(str) > len(res) {
            res = str
        }
        str = spread(runes, i, i+1)
        if len(str) > len(res) {
            res = str
        }
    }
    return res
}

func max(a, b int) int {
    if a > b {
        return a 
    }
    return b
}

func spread(runes []rune, left, right int) string {
    for left >= 0 && right < len(runes) {
        if runes[left] == runes[right] {
            left--
            right++
        }else {
            break
        }
    }
    return string(runes[left+1:right])
}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看