您的位置:首页 > 编程语言 > Python开发

LeetCode 5.Longest Palindromic Substring (Python)兼翻译

2017-02-07 17:52 513 查看

5. Longest Palindromic Substring

最长回问子串

本题来自LeetCode OJ

题目翻译

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

给定一个字符串s,找出s中的最长回文子串。你可以假定s的最大长度为1000。

例1:

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


例2:

Input: "cbbd"
Output: "bb"


题目分析

回文的特点就是正着和反着是相同的,或者说是镜面的。所以用sr表示倒叙后的s字符串,如果他是回文子串的一个充要条件就是它存在sr中且本身为回文。

代码示例

class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:type sr: str
:rtype: str
"""
sr = "".join(reversed(s)) # sr为s的倒序
answerLen = 1 # 最短的回文子串即为一个字符
try:
answer = s[0] # 取第一个字符作为默认回文
except:
return None
i = 0
# 因为最后一个字符肯定不需要去判断
while i < len(s) - 1:
plus = 2
# plus-1为回文的字符串的现有长度,致所有加plus<=len(s)的判断条件是由于避免出现s本身为回文
while sr.find(s[i:i+plus]) != -1 and plus <= len(s)-i:
plus = plus + 1
if plus-1 > answerLen:
taskAnswer = s[i:i+plus-1]
# 这时候需要判断备选的答案本身是否为回文
if taskAnswer == taskAnswer[::-1]:
answer = taskAnswer
answerLen = len(answer)
i = i + 1
return answer
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode Algorithm