LeetCode 笔记十 2019/10/6
这两天有点事情,晚上没有时间刷题,但不想落下啊!
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
example
example 1
Input: [“flower”,“flow”,“flight”]
Output: “fl”
example 2
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Code
一开始想歪了,取出了最长跟最短的字符串进行对比:
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
elif len(strs) == 1:
return strs[0]
minStr = min(strs, key = len)
maxStr = max(strs, key = len)
r = ''
for i, j in zip(minStr, maxStr):
if i == j:
r += i
else:
break
del minStr, maxStr
return r
结果当然报错了:
input : ["flower","flow","flight"]
Output : "flow"
Expected : "fl"
后来发现直接对strs
进行排序后再作对比就ok了:
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
elif len(strs) == 1:
return strs[0]
strs.sort()
r = ''
for i, j in zip(strs[0], strs[-1]):
if i == j:
r += i
else:
break
return r
结果:
118 / 118 test cases passed.
Runtime: 36 ms
Memory Usage: 13.7 MB
Runtime: 36 ms, faster than 91.40% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.7 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.
国庆期间一直在做一个理论的算法推导,秃头了难顶呀。这两天又开始准备一个CCF的比赛,冲吧~