[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
}

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