码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode5:Longest Palindromic Substring@Python

时间:2016-11-22 22:52:05      阅读:403      评论:0      收藏:0      [点我收藏+]

标签:smp   dnn   orm   i+1   ams   vss   tab   append   alt   

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

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"


动态规划法:以"ababae"为例:
技术分享
 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         sLength=len(s)
 8         begin=0
 9         length=0
10         table=[]
11         for i in range(sLength):
12             tem=[]
13             for j in range(sLength):
14                 tem.append(0)
15             table.append(tem)
16             
17         for i in range(sLength):
18             table[i][i]=1
19 
20         for i in range(sLength-1):
21             if s[i]==s[i+1]:
22                 table[i][i+1]=1
23                 begin=i
24                 length=1
25             
26         for tem in range(1,sLength):
27             for i in range(sLength-tem):
28                 j=i+tem
29                 if (s[i]==s[j] and table[i+1][j-1])==1:
30                     table[i][j]=1
31                     length=tem
32                     begin=i
33 
34         return s[begin:begin+length+1]

 












Leetcode5:Longest Palindromic Substring@Python

标签:smp   dnn   orm   i+1   ams   vss   tab   append   alt   

原文地址:http://www.cnblogs.com/mzct123/p/6091226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!