[LeetCode] Longest Palindromic Substring

題目鏈接:https://leetcode.com/problems/longest-palindromic-substring/

description:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

palindromic string(迴文字符串),- - 懵了一臉的我去google了一些,通俗地解釋就是不管從左到右還是從右往左,讀到的字符串都是一樣的 - - 

方案一:

這個方法提交後性能簡直慘不忍睹,先貼出來,後續會繼續優化

func longestPalindrome(s string) string {
    if "" == s {
        return ""
    }
    bytes := []byte(s)
	curEnd := len(s) - 1
	curHead := 0
	ret := string(bytes[0])

	for curHead < len(s)-1 {
		if curEnd == curHead {
			curHead++
			curEnd = len(s) - 1
			continue
		}
		if bytes[curHead] != bytes[curEnd] {
			curEnd--
			continue
		}
		h := curHead + 1
		e := curEnd - 1
		for {
			if h >= e {
				if len(ret) < (curEnd - curHead + 1) {
					ret = string(bytes[curHead : curEnd+1])
				}
				break
			}
			if bytes[h] != bytes[e] {
				break
			}
			h++
			e--
		}
		curEnd--
	}
	return ret
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章