当前位置:网站首页>Leetcode daily question - 28 Implement strstr() (simple)
Leetcode daily question - 28 Implement strstr() (simple)
2022-06-25 20:13:00 【Cheng Xiaoqi】
String matching problem : There are generally two methods : Violence matching method and kmp Algorithm
Method 1 : Violence solution
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
haystack_length = len(haystack)
needle_length = len(needle)
i = 0
while i+needle_length <= haystack_length:
flag = True
for j in range(0,needle_length):
if haystack[i+j] != needle[j]:
flag = False
break
if flag:
return i
i += 1
return -1
# Adapted from the official java Code

Time limit exceeded , Maybe the last instance is too long .
Method 2 :kmp Algorithm
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a=len(needle)
b=len(haystack)
if a==0:
return 0
next=self.getnext(a,needle)
p=-1
for j in range(b):
while p>=0 and needle[p+1]!=haystack[j]:
p=next[p]
if needle[p+1]==haystack[j]:
p+=1
if p==a-1:
return j-a+1
return -1
def getnext(self,a,needle):
next=['' for i in range(a)]
k=-1
next[0]=k
for i in range(1,len(needle)):
while (k>-1 and needle[k+1]!=needle[i]):
k=next[k]
if needle[k+1]==needle[i]:
k+=1
next[i]=k
return next
# This code refers to 「 Random code recording 」
Such a classic kmp The algorithm is really brain - burning , So I decided to write a separate article kmp Summary of the algorithm
边栏推荐
猜你喜欢

Transunet reading notes

Pta--7-20 exchange minimum and maximum (15 points)

2020-11-14-Alexnet

Pcl+vs2019+opencv environment configuration

206. reverse linked list (insert, iteration and recursion)

My official account writing experience sharing

<C>. Rolling phase division

<C>. tic-tac-toe

Now meditation: crash service and performance service help improve application quality

Applet password input box
随机推荐
PAT B1081
Go language installation and uninstallation
DICOM to NII
2.5 find the sum of the first n terms of the square root sequence
Panda weekly -2022/02/18
Teach you how to add custom controls to a map
Nnformer reading notes
Please do not call Page constructor in files
在打新债开户证券安全吗?低佣金靠谱吗
在打新債開戶證券安全嗎?低傭金靠譜嗎
Life cycle function of composite API
2.17(Avoid The Lakes)
node. JS express connect mysql write webapi Foundation
在打新债开户证券安全吗
Installing or uninstalling VMware could not find the network location
Number of wechat applet custom input boxes
Share a billing system (website) I have developed
Uniapp waterfall flow, applet waterfall flow, very simple, suitable for the whole platform
Arduino ide + esp8266+mqtt subscribe to publish temperature and humidity information
PAT B1053