题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。`
我的解法——垂直扫描(AC)
- 垂直扫描。
- 复杂度O(S),S为字符串数组中所有字符串长度之和。
- Beat11%
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if(len(strs) == 0):
return ""
min_length = len(strs[0])
for i in range(len(strs)):
if(len(strs[i]) < min_length):
min_length = len(strs[i])
for i in range(min_length):
flag = True
now = strs[0][i]
for j in range(1,len(strs)):
if(strs[j][i] != now):
flag = False
break
if(not flag):
return strs[0][:i]
elif(i == min_length - 1):
return strs[0][:min_length]
return ""
#其他解法——Divide and Conquer
- 见leetcode解答
- 复杂度:O(s)
其他解法——横向遍历
- 见leetcode解答
- 复杂度:O(s)
其他解法——二分法
- 见leetcode解答
- 复杂度O(S·logn)
- 首先我们找出最短的字符串,最长的前缀的长度不会超过这个字符串。然后我们使用二分搜索的方式。
参考答案
- https://leetcode.com/problems/longest-common-prefix/solution/
- https://www.jianshu.com/p/63dcc0d7db75