在Python中实现strStr()
假设我们有两个字符串str和sub_str。我们必须在str中找到sub_str的第一个匹配项。因此,如果字符串str为“helloworld”,子字符串为“lo”,则结果将为3。
这可以使用strstr()C中的函数来完成。我们必须设计另一个类似于strstr()C中的函数。
为了解决这个问题,请遵循以下步骤-
i:=0,j:=0,m:=sub_str的长度和n:=str的长度
如果m=0,则返回0
当i<n和n–i+1=m时,
温度:=j
当j<m和i<n且sub_str[j]==str[j]时,
如果j=m,则返回温度
我:=温度+1
j:=0
将i和j加1
如果str[i]=sub_str[j],则
否则我加1
返回-1
让我们看一下实现以获得更好的理解
范例(Python)
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
i = 0
j = 0
m = len(needle)
n = len(haystack)
if m ==0:
return 0
while i<n and n-i+1>=m:
if haystack[i] == needle[j]:
temp = i
while j<m and i<n and needle[j]==haystack[i]:
i+=1
j+=1
if j == m:
return temp
i= temp+1
j = 0
else:
i+=1
return -1
haystack = "helloworld"
needle = "lo"
ob1 = Solution()print(ob1.strStr(haystack, needle))输入值
haystack = "helloworld" needle = "lo"
输出结果
3