LeetCode 笔记四 (2019/09/26)
程序员文章站
2022-04-02 21:21:04
...
LeetCode 笔记四
Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
简单点说就是判断回文。
Example
example1
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
example2
Input: “cbbd”
Output: “bb”
Code
之前几道题基本上都用字典可以很高效的完成,于是一开始我也用了字典:
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) == 0:
return s
Dict = {}
r = ''
for i, c in enumerate(s):
if (c in Dict):
if (s[Dict[c]:i+1] == s[Dict[c]:i+1][::-1]) and (len(r) < len(s[Dict[c]:i+1])):
r = s[Dict[c]:i+1]
else:
Dict[c] = i
if len(r) == 0:
return s[0]
else:
return r
仔细看这个代码,会发现这个代码是错的。这里是将str作为字典的键,在这个代码中,只保存了第一次记录到同一个str的索引,这样无法同时记录中间多个索引,提交果然报错了,看错误的地方比较好理解一点:
Input: "babadada"
Output: "bab"
Expected: "adada"
于是我将索引保存为字典的键,对代码进行了修改:
class Solution:
def get_key(self, dct, value):
return list(filter(lambda x:dct[x] == value, dct))
def longestPalindrome(self, s: str) -> str:
if len(s) == 0:
return s
Dict = {}
r = ''
for i, c in enumerate(s):
if c in Dict.values():
temp = self.get_key(Dict, c)
for j in temp:
if (s[j:i+1] == s[j:i+1][::-1]) and (len(r) < len(s[j:i+1])):
r = s[j:i+1]
Dict[i] = c
if len(r) == 0:
return s[0]
else:
return r
这次提交正确了,不过效果是真的不是很好:
103 / 103 test cases passed.
Runtime: 6544 ms
Memory Usage: 13.8 MB
Runtime: 6544 ms, faster than 13.06% of Python3 online submissions for Longest Palindromic Substring.
Memory Usage: 13.8 MB, less than 22.69% of Python3 online submissions for Longest Palindromic Substring.
其实看这段代码,可以发现这代码用了两次循环…还不如不用字典,直接循环遍历:
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) == 0:
return s
r = ''
for i in range(len(s)):
for j in range(len(s), i, -1):
if len(r) >= j-i:
break
elif s[i:j] == s[i:j][::-1]:
r = s[i:j]
break
return r
这样看起来还比较容易理解,提交结果还比字典好了一丢丢:
103 / 103 test cases passed.
Runtime: 5596 ms
Memory Usage: 13.9 MB
Runtime: 5596 ms, faster than 17.25% of Python3 online submissions for Longest Palindromic Substring.
Memory Usage: 13.9 MB, less than 22.69% of Python3 online submissions for Longest Palindromic Substring.
一点题外话…每天都忘记过来更新…继续冲啊!再过一年半就要开始为了找工作而血战,为了生存,用《杀手界》的一句话来说,只有拼啦!