leetcode 5(目前没有参考价值的一篇博客)
题目描述
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"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目解析
-
思路一
一开始想用字符串匹配来做:将字符串反转,反转前的字符串与反转后的字符串进行匹配,找到最长的回文子串
def longestPalindrome(s):
if s == '':
return ''
if len(s) == 1:
return s
temp = s[::-1]
result = []
i = 1
count = 0
k = 1
while i <= len(s) and k < len(s):
str1 = s[: 0 + i]
str2 = temp[-1 - i + 1:]
if i == len(s) and count != 0:
str1 = s[k: i]
str2 = temp[-i: -k]
k = k + 1
if i == len(s):
count = 1
j = 0
m = j
result_part = []
while j < len(str1):
if str1[j] == str2[j]:
result_part.append(str1[j])
if j - 1 != m:
result_part.pop()
m = j
j = j + 1
result_part = ''.join(result_part)
result.append(result_part)
if i < len(s):
i = i + 1
else:
i = len(s)
i = 0
index = i
length = len(result[i])
while i < len(result):
if len(result[i]) > length:
index = i
length = len(result[i])
i = i + 1
return result[index]
if __name__ == '__main__':
s = 'ccc'
print(longestPalindrome(s))
这种思路搞了很久也没搞出来,上面的代码是不完善的,有些特殊情况并没有处理完善。需要注意的条件、边界很多,没有完全解决,现在看来并不是一种好思路。今天是没有时间了,之后看能不能搞出来吧
- 思路二
最简单粗暴的方法就是遍历输入字符串的所有子串,每一个都判断是否为回文串,挑选出长度最长的回文串,但是时间复杂度太高了
class Solution:
def longestPalindrome(self, s: str) -> str:
if s == '':
return ''
if len(s) == 1:
return s
max_length = 0
result = ''
i = 0
length = len(s)
max = 0
# 遍历子串,依次判断是否为回文串
while i < length:
j = i + 1
while j <= length:
substring = s[i: j + 1]
if self.isPalindrome(substring) and len(substring) > max:
max = len(substring) # 存储最长回文串的长度
result = substring # 存储最长回文串
j = j + 1
i = i + 1
return result
# 判断是否为回文串
def isPalindrome(self, s):
length = len(s)
i = 0
while i < length / 2:
if (s[i] != s[length - i - 1]):
return False
i = i + 1
return True
上面的代码使用了两个while循环,导致代码的时间复杂度为 O ( n 2 ) O(n^2) O(n2)
今天的时间不够用了,在思路一上浪费了太多时间也没有做出来。看答案还有好几种思路,今天就到这里了,明天接着总结。