leetcode.0014. Longest Common Prefix

leetcode.0014. Longest Common Prefix

题目

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: ["flower","flow","flight"]
Output: "fl"

Example 2:

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

Note:

All given inputs are in lowercase letters a-z.

作者答案(python3):

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """

        t=0
        strs_len = len(strs)
        s_out = ''
        if strs_len == 0:  # 排除: []
            return s_out
        for i in range(strs_len):
            if strs[i] == '' : # 排除: [...,'',...]
                return s_out
                break
        while len(min(strs))>t:# 最小字符串的长度
            if [strs[0][t]]*(strs_len) == [strs[i][t] for i in range(strs_len)]: 
                s_out += strs[0][t]
                t += 1
            else:
                break
        return s_out

参考答案(python3):

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        lets = list(map(set, zip(*strs)))# 例如:strs =['sd','sd','sdw'], 
                                         # 则 lets = [{'s'},{'d'}]。
        out = ""
        while lets and len(lets[0]) == 1:
            out += list(lets[0])[0]
            lets = lets[1:]
        return out

猜你喜欢

转载自blog.csdn.net/qq_37954325/article/details/81140993
今日推荐