首页 > 其他 > 详细

【LeetCode】5. Longest Palindromic Substring

时间:2017-01-14 19:48:56      阅读:305      评论:0      收藏:0      [点我收藏+]

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"

题意:求最长回文串。

思路:我是从discuss区看到的,整体思路事从用两个指针j,k从内往外遍历,当遇到不能使回文成立的条件时,更新最大值记录

 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         if len(s)==0: return ‘‘
 8         if len(s)==1: return s
 9         front = 0
10         l = 0
11         for i in range(len(s)):
12             if len(s)-i<l/2: break #当后面的字符串已经不能更新最大值时
13             j = k = i
14             while k+1<len(s) and s[k] == s[k+1]: k += 1 #跳过一样的字符
15             while j>0 and k+1<len(s) and s[j-1] == s[k+1]:  #从里往外遍历
16                 j -= 1
17                 k += 1
18             if k-j+1 > l:
19                 front = j
20                 l = k-j+1
21         return s[front:front+l]

 

【LeetCode】5. Longest Palindromic Substring

原文:http://www.cnblogs.com/fcyworld/p/6285938.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!