【LeetCode】5. Longest Palindromic Substring

解析:两重循环,第二重循环是向两边扩展,判断是否相等。

func searchPalindrome(s string, left int, right int, start *int, radius *int) {
	step := 1
	len := len(s)
	for left-step >= 0 && right+step < len {
		if s[left-step] != s[right+step] {
			break
		}
		step++
	}
	wide := right-left+2*step-1
	if *radius < wide {
		*radius = wide
		*start = left-step+1
	}
}

func longestPalindrome(s string) string {
	start, radius := 0, 0
	left, right := 0, 0
	len := len(s)
	if len == 1 {
		return s
	}
	for index := 0; index < len-1; index++ {

		if s[index] == s[index+1] {
			left = index
			right = index+1
			searchPalindrome(s, left, right, &start, &radius)
		}
		
		left, right = index, index

		searchPalindrome(s, left, right, &start, &radius)

		if radius == 0 {
			radius = len
		}

	}

	return s[start : start+radius]
}

  

posted on 2018-02-01 21:15  小问号???  阅读(79)  评论(0)    收藏  举报

导航