leetcode 5. Longest Palindromic Substring
2016-02-26 00:28
267 查看
给一个字符串求最长公共字串。直接上o(n)的Manacher,方法网上很多讲的都挺详细,需要的自行百度吧
class Solution(object):
def pre(self,s):
lenS = len(s)
i = 0
res = []
while i < lenS:
res.append('#')
res.append(s[i])
i+=1
res.append('#')
return res
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ss = self.pre(s)
lenS = len(ss)
p = [1 for i in range(lenS+1)]
id = 0
mx = 0
i = 0
while i < lenS:
if mx > i :
p[i] = min(p[id*2-i],p[id]+id-i)
else : p[i] = 1
while i - p[i] >= 0 and i+p[i] < lenS and ss[i+p[i]] == ss[i-p[i]]: p[i] += 1
if (p[i] + i > mx):
mx = p[i] + i
id = i
i += 1
ans = 0
i = 0
id = 0
while i < lenS:
if (ans < p[i]):
ans = p[i] - 1
id = i // 2
i += 1
id = id - ans // 2
return s[id:id+ans]
class Solution(object):
def pre(self,s):
lenS = len(s)
i = 0
res = []
while i < lenS:
res.append('#')
res.append(s[i])
i+=1
res.append('#')
return res
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ss = self.pre(s)
lenS = len(ss)
p = [1 for i in range(lenS+1)]
id = 0
mx = 0
i = 0
while i < lenS:
if mx > i :
p[i] = min(p[id*2-i],p[id]+id-i)
else : p[i] = 1
while i - p[i] >= 0 and i+p[i] < lenS and ss[i+p[i]] == ss[i-p[i]]: p[i] += 1
if (p[i] + i > mx):
mx = p[i] + i
id = i
i += 1
ans = 0
i = 0
id = 0
while i < lenS:
if (ans < p[i]):
ans = p[i] - 1
id = i // 2
i += 1
id = id - ans // 2
return s[id:id+ans]
相关文章推荐
- GenyMotion不能启动的问题,Unable to start the virtual device.VirtualBox cannot start the virtual device
- Android Volley完全解析(四),带你从源码的角度理解Volley
- Android Volley完全解析(三),定制自己的Request
- 创业全攻略:从零到开具第一张发票
- Heap和stack有什么区别?
- Leetcode 160:Intersection of Two Linked Lists
- Android Volley完全解析(二),使用Volley加载网络图片
- Disjoint-Set并查集
- Android Volley完全解析(一),初识Volley的基本用法
- UVA 1368(p58)----DNA Consensus String
- jedis 源码阅读三——PipeLine
- Python学习笔记day6
- 自学vim笔记
- UVA 1363(p338)----Joseph's Problem
- C++ 内存分布,编译与运行阶段探索?(暂时不确定标题)
- MongoDB性能优化
- Hibernate.initialize(Obj)用法
- UVA 1354(p197)----Mobile Computing
- hibernate里的session.get()和session.load()区别以及Hibernate.initialize(Obj)用法
- BigInteger大整数类高精度