1. 程式人生 > >LeetCode刷題_14. Longest Common Prefix

LeetCode刷題_14. Longest Common Prefix

原題連結:https://leetcode.com/problems/longest-common-prefix/description/

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
        """
        if len(strs) == 0:
            common_seq = ""
        else:
            common_seq =
strs[0] for string in strs: len_string = len(string) len_common = len(common_seq) if len_common == 0: common_seq = "" break length = min(len_string,len_common) temp = [] for i in range(length)
: if string[i] == common_seq[i]: temp.append(string[i]) else: break common_seq = ''.join(temp) return common_seq