This article is participating in Python Theme Month. See the link to the event for more details

review

A brush solution ideas see: juejin.cn/post/698914…

describe

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: strs = ["flower","flow","flight"]
Output: "fl"
Copy the code

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Copy the code

Note:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
Copy the code

parsing

Find the common longest prefix string (LCP) for all strings in the STRS list, or return an empty string if there is no LCP. Python is a powerful language that came into being with the motto “life is short, I use Python.” We can use Python’s built-in function zip to solve this LCP problem. Will all the elements in the STRS first combined into a set of characters, then determine whether the length of the collection to one, if for a character to the result string appended to the results, and then determine a combination of all elements of the second character set for a length, so on whether all elements of the first n characters; If the set length is not one, then the characters are not all equal and result is returned.

answer

class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not(strs): return "" result = "" for s in zip(*strs): if len(set(s)) ! = 1: return result result += s[0] return resultCopy the code

The results

Runtime: 10000 ms, the linked list for Longest Common Prefix in the linked list. 10000 MB, less than 88.38% of Python online submissions for Longest Common Prefix.Copy the code

expand

The zip function takes an iterable object as an argument, packages the corresponding elements of the object into tuples, and returns a list of those tuples. If the iterators do not have the same number of elements, the list is returned with the same length as the shortest object. Using the * operator, you can decompress the tuple into a list. For example:

A = [1,2,3] b = [4,5,6] c = [4,5,6,7,8]Copy the code

Usage:

Print ([x for x in d])Copy the code

Print:

[(1, 4), (2, 5), (3, 6)]
Copy the code

Use 2:

E = zip(a,c) # print([x for x in e])Copy the code

Print:

[(1, 4), (2, 5), (3, 6)]
Copy the code

Use 3:

F = zip(*zip(a,b)) # print(x for x in f)Copy the code

Print:

[(1, 2, 3), (4, 5, 6)]
Copy the code

Link: leetcode.com/problems/lo…

Your support is my greatest motivation