leetcode14

14. Longest Common Prefix

Description

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:

1
2
Input: ["flower","flow","flight"]
Output: "fl"

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs or len(strs) == 0:
return ""

for i, strs_ in enumerate(zip(*strs)):
if len(set(strs_)) > 1:
return strs[0][:i]

return min(strs)

Python

zip(*)

1
2
3
arr = ["flower","flow","flight"]
for group in zip(*arr):
print(group)

(‘f’, ‘f’, ‘f’)
(‘l’, ‘l’, ‘l’)
(‘o’, ‘o’, ‘i’)
(‘w’, ‘w’, ‘g’)
zip(*) unpack

min()

1
print(min(arr))

flight