Goang Leetcode 5. Longest Palindromic Substring.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89067084

思路

dp算法
DP[i,j]=false:表示子串[i,j]不是回文串。DP[i,j]=true:表示子串[i,j]是回文串。
DP[i,i]=true:当且仅当DP[i+1,j-1] = true && (s[i]==s[j])
否则DP[i,j] =false;

code


func longestPalindrome(s string) string {
	str := []byte(s)
	l := len(str)
	if l == 0 {
		return ""
	}
	dp := make([][]bool, l)
	for k := range dp {
		dp[k] = make([]bool, l)
	}
	ret := []byte{}
	max := 0
	for i := l - 1; i >= 0; i-- {
		for j := i; j < l; j++ {
			if str[i] == str[j] && (j-i <= 2 || dp[i+1][j-1]) {
				dp[i][j] = true
				if max < j-i+1 {
					max = j - i + 1
					ret = str[i : j+1]
				}
			}
		}
	}
	return string(ret)
}

更多内容请移步我的repo:https://github.com/anakin/golang-leetcode

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/89067084
今日推荐