目录

14 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “"。

示例 1:

1
2
输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

所有输入只包含小写字母 a-z 。
# -*- coding: utf-8 -*-
# @Time     : 2018/12/2 22:48
# @Author   : affectalways
# @Site     : 
# @Contact  : affectalways@gmail.com
# @File     : 14.py
# @Software : PyCharm 

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        length = len(strs)
        if length == 0 or (length == 1 and strs[0] == ''):
            return ""
        result = []

        min_length = len(min(strs, key=len))

        index = 0
        while index < min_length:
            flag = True
            all = None
            for value in strs:
                if all is None:
                    all = value[index]
                    continue
                if all == value[index]:
                    continue
                else:
                    flag = False
                    break

            if not flag:
                break
            else:
                index += 1
                result.append(all)
        return ''.join(result)


if __name__ == '__main__':
    solution = Solution()
    # print(solution.longestCommonPrefix(["flower", "flow", "flight"]))
    print(solution.longestCommonPrefix(["", ""]))