String 5. Longest Palindromic Substring

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

解答:
class Solution:
	def preProcess(self, s):
		length = len(s)
		if length == 0:
			return '^$'
		ret = '^'
		for i in range(length):
			ret += '#' + s[i]

		ret += '#$'
		return ret

	def longestPalindrome(self, s):
		'''
		1) 维护C, L, R, 使R最大
		2)如果关于C的镜像在[L,R]内,则p[i] = p[i']
		3) 不在[L, R]内则从R+1开始验证
		'''
		C = R = 0
		s = self.preProcess(s)
		maxlen = len(s)
		P = [0 for i in range(maxlen)]
		for i in range(1, maxlen-1):
			i_ = 2*C - i
			P[i] = min(R-i, P[i_]) if R > i else 0

			while s[i + 1 + P[i]] == s[i - 1 - P[i]]:
				P[i] += 1

			if i + P[i] > R:
				C = i
				R = i + P[i]

		max = center = 0
		for i in range(maxlen):
			if P[i] > max:
				max = P[i]
				center = i

		return ''.join([x for x in s[center-max : center+max] if x != '#'])

猜你喜欢

转载自blog.csdn.net/ddl_xiaodichen/article/details/80164764