1、最长公共前缀(14)
题目描述:
题解一:
- 利用zip(*)函数功能,将字符串的一一对应元素组合到列表中
- 然后通过集合去重性判断每一个列表集合长度是不是1来决定前缀是否一致
【python3 代码】
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res=""
for tmp in list(zip(*strs)):
tmp_set=set(tmp)
if len(tmp_set)==1:
res+=tmp[0]
else:
break
return res
题解二:二分查找
后续补充
2、实现strStr()(28)
题目描述:
题目链接
题解一:子串逐一比较
- 将长度为needle长度的滑动窗口沿着 haystack 字符串逐步移动,并将窗口内的子串与 needle 字符串相比较,若相等,则返回第一字符所对应索引
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
L=len(haystack)
R=len(needle)
for i in range(L-R+1):
if haystack[i:i+R]==needle:
return i
return -1
-
时间复杂度: O ( ( N − R ) R ) O((N - R)R) O((N−R)R),其中 N 为 haystack 字符串的长度,R 为 needle 字符串的长度。内循环中比较字符串的复杂度为 R,总共需要比较 (N - R) 次。
-
空间复杂度:O(1)O(1)。
题解二:双指针
题解三:KMP