题目描述:
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 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
思路:
求最长前缀字符串,首先要找到最短的那个单词,最长前缀字符串的长度不会超过该单词。并且在这个最短单词上找到公共最长位置i,最后直接输出关于最短单词[:i]即可。
代码:
class Solution:
def longestCommonPrefix(self, strs) -> str:
if strs == None or strs == []: return ''
shor = min(strs,key=len)
i = 0
flag = False
while i < len(shor):
char = shor[i]
for s in strs:
if s[i] != char:
flag = True
if flag:
break
i += 1
return shor[:i]
知识点:
max/min函数的技巧和应用:
初级:
print(max(1,2,5,2))
output: 5
a = [1,2,5,2]
print(max(a))
output: 5
中级:
a=[1,-2,3,-10,0]
print(max(a,key=abs))
output: -10
高级
#求商品最便宜的是哪个
prices = {
'A':123,
'B':450.1,
'C':12,
'E':444,
}
k = min(prices,key=lambda v:prices[v])
print(k)
output: C