forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.py
More file actions
49 lines (36 loc) · 1.02 KB
/
LongestCommonPrefix.py
File metadata and controls
49 lines (36 loc) · 1.02 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/3 17:12
# @Author : tc
# @File : LongestCommonPrefix.py
"""
题号 14 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
可以用字典树解决
"""
from typing import List
class Solution:
# 暴力解法
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ''
min_str = min(strs)
common_prefix = ''
for i in range(len(min_str)):
for _str in strs:
if _str[i] != min_str[i]:
return common_prefix
common_prefix += min_str[i]
return common_prefix
if __name__ == '__main__':
strs = ["dog","racecar","car"]
solution = Solution()
print(solution.longestCommonPrefix(strs))