高级编程技术作业_15 leetcode练习题

14. 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.

解题思路:

对所有字符串依次进行逐字符对比,很容易得出最长前缀。

代码展示

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if strs:
            flag = 0
            i = -1
            while flag == 0:
                ch = strs[0][i + 1]
                for str in strs:
                    if str[i + 1] != ch:
                        flag = 1
                        break
                if flag == 0:
                    i += 1
            if i != -1:
                return strs[0][:i + 1]
            else:
                return ""

        return ""

猜你喜欢

转载自blog.csdn.net/akago9/article/details/80161228