LeetCode 100 questions 14. Longest common prefix Python3

@LeetCode

LeetCode 100 Question 14. Longest Common Prefix

topic

Write a function to find the longest common prefix in an array of strings.

Returns the empty string "" if no common prefix exists.

example

Input: strs = ["flower", "flow", "flight"]
Output: "fl"

analyze

Using python's zip function, treat str as a list and then treat the input as a two-dimensional array, left-aligned and compressed vertically, and then use the set to deduplicate each item, and then traverse the list to find the common prefix before the element length is greater than 1.

The zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list composed of these tuples.

If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object, and the tuple can be decompressed into a list by using the * operator.

the code

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        str1=''
        zipped = zip(*strs)
        l1 = list(zipped)
        for i in l1:
            if len(set(i)) == 1:  # 集合长度为1,即只有一个相同元素
                str1 += i[0]
            else:
                break
        return str1
            

operation result

result graph

おすすめ

転載: blog.csdn.net/weixin_45818370/article/details/123857301