topic:
14. The longest common prefix
Write a function to find the longest common prefix in an array of strings.
If there is no common prefix, an empty string "" is returned.
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for input.
prompt:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] only consists of lowercase English letters
Problem solution ideas:
First use zip(*li) to pack the elements of the string array, and then use the set() function to deduplicate. If the length of the deduplicated element is 1, it is a common prefix.
Problem solution python code:
class Solution(object):
def longestCommonPrefix(self, strs):
s = ""
# print(list(zip(*strs)))
for i in list(zip(*strs)):
ss = set(i)
# print(ss)
if len(ss) == 1:
s += ss.pop()
else:
break # 只要有一个不是一就跳出
return s
Author: a-qing-ge
links: https://leetcode-cn.com/problems/longest-common-prefix/solution/ziplistmiao-yong-niu-bi-pi-liao-by-a-qin-ul61/
sources :LeetCode https://leetcode-cn.com/problems/longest-common-prefix/