题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution:
def longestCommonPrefix(self , strs: List[str]) -> str:
target = ""
minL = 5001
# 找到最短的字符串
for i in strs:
if len(i) < minL:
minL = len(i)
target = i
while target:
count = 0
for i in range(len(strs)):
if target not in strs[i]:
break
else:
count += 1
if count == len(strs):
break
target = target[:len(target)-1]
return target
解题思路
- 先遍历字符串数组,得到最短的字符串,作为目标字符串;
- 遍历字符串数组,判断目标字符串是否在所有的字符串中,如果不是,则将目标字符串的最后一位去掉,进行下一轮的比较;如果是,则返回当前目标字符串。
复杂度
- 时间复杂度为(n*len);
- 空间复杂度为O(1)。
查看14道真题和解析