LeetCode Everyday:坚持价值投资,做时间的朋友!!!
题目:
实现 strStr() 函数。
给定一个haystack
字符串和一个needle
字符串,在haystack
字符串中找出needle
字符串出现的第一个位置 (从0开始)。
如果不存在,则返回 -1。如果needle
是空字符串,返回 0
示例:
- 示例 1:
输入: haystack = "hello", needle = "ll" 输出: 2
- 示例 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
代码
方法一: Sunday解法 题解
执行用时:56 ms, 在所有 Python3 提交中击败了50.34%的用户
内存消耗:14.7 MB, 在所有 Python3 提交中击败了8.16%的用户
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# Func: 计算偏移表
def calShiftMat(st):
dic = {}
for i in range(len(st)-1,-1,-1):
if not dic.get(st[i]):
dic[st[i]] = len(st)-i
dic["ot"] = len(st)+1
return dic
# 其他情况判断
if len(needle) > len(haystack):return -1
if needle=="": return 0
# 偏移表预处理
dic = calShiftMat(needle)
idx = 0
while idx+len(needle) <= len(haystack):
# 待匹配字符串
str_cut = haystack[idx:idx+len(needle)]
# 判断是否匹配
if str_cut==needle:
return idx
else:
# 边界处理
if idx+len(needle) >= len(haystack):
return -1
# 不匹配情况下,根据下一个字符的偏移,移动idx
cur_c = haystack[idx+len(needle)]
if dic.get(cur_c):
idx += dic[cur_c]
else:
idx += dic["ot"]
return -1 if idx+len(needle) >= len(haystack) else idx
"""
For Example: input: haystack = "hello", needle = "ll"
output: 2
"""
haystack = "hello"
needle = "ll"
solution = Solution()
result = solution.strStr(haystack, needle)
print('输出为:',result)
方法二: 看needle是不是haystack的一个子串 题解
执行用时:44 ms, 在所有 Python3 提交中击败了61.81%的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了6.67%的用户
class Solution:
def strStr1(self, haystack: str, needle: str) -> int:
for i in range(0, len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
def strStr2(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
"""
For Example: input: haystack = "hello", needle = "ll"
output: 2
"""
haystack = "hello"
needle = "ll"
solution = Solution()
result1 = solution.strStr1(haystack, needle)
result2 = solution.strStr2(haystack, needle)
print('不使用内置函数输出为:%d,使用内置函数输出为:%d' % (result1, result2))
参考
- https://leetcode-cn.com/problems/implement-strstr/solution/python3-sundayjie-fa-9996-by-tes/
- https://leetcode-cn.com/problems/implement-strstr/solution/python-1xing-by-knifezhu-8/