LeetCode: (14. The longest common prefix!!!!!)

Topic:
14. Longest Common Prefix
Write a function to find the longest common prefix in a string array.

If there is no common prefix, an empty string "" is returned.

Example 1:

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

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for input.
Note:
All input only contains lowercase letters az.

Problem-solving ideas:
1. Simply put, this problem can use set set (), the nature of the set can be removed from repetition.
2. The zip() function will also be used, and the Python code will be introduced later in the article
:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        none = ""
        if len(strs) == 0:
            return ""
        for a in zip(*strs):
            if len(set(a)) == 1:
                none += a[0]
            else:
                return none
        return none

operation result:
Insert picture description here

zip() function:

The definition of the zip() function:
take elements from multiple iterators in the parameters and combine them into a new iterator;
return:
return a zip object whose internal elements are tuples; can be converted into lists or tuples;
pass in parameters :
Iterators for tuples, lists, dictionaries, etc.
Usage of the zip() function:
When there is only one parameter in the zip() function, zip(iterable) takes a tuple from iterable in turn to form a tuple.
example:

#zip()函数单个参数
list1 = [1, 2, 3, 4]
tuple1 = zip(list1)
#打印zip函数的返回类型
print("zip()函数的返回类型:\n", type(tuple1))
# 将zip对象转化为列表
print("zip对象转化为列表:\n", list(tuple1))

Output result:
The return type of the zip() function:
<class'zip'>
Convert the zip object into a list:
[(1,), (2,), (3,), (4,)]

Guess you like

Origin blog.csdn.net/Kinght_123/article/details/109287672