Problem Description:
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"
思路:
刚开始使用了两层循环 不出所料 超时了。
最后O(n) < = C <= O()
将字符串翻转进行从头判断,先单个判断因为有可能没有回文字符串 那么就取原字符串第一个字符,如果不是回文就后移一位继续之前的操作。
这样遗漏了一个异常,准确的说是超时问题。由于复杂度是有可能达到平方的,即在一个比较长的全是同一字符的字符串时就达到了, 如果照常计算会增加耗时,导致整体用例通不过。所以可以单独处理这个样例。直接通过判断翻转后的字符串是否等于源字符串。
My Solution:
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
maxLen = tempLen = 0
res = ""
i = 0
s2 = s[::-1]
# 首先处理特例 判断全同一字符的字符串
if s2 in s:
return s
# 进行寻找回文字符串
while i < n:
j = i+1 # 节省时间跳过判空处理
while j <= n:
if s2[i:j] in s: # 如果翻转后的 “字符串” 在原字符串中出现
# 极有可能是回文 进行下一步判断
tempS2 = s2[i:j]
if tempS2==tempS2[::-1]: # 判断该字符串是否是回文字符串
tempLen = len(tempS2)
if tempLen > maxLen:
res = tempS2
maxLen = tempLen
j += 1
else: # 否则 直接从下一个字符开始 重复上述操作
break
i += 1
# if n!=0 and len(res)
return res