GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/028_Implement_strStr().py at master · 539961733/leetcode

Expand file tree

/

028_Implement_strStr().py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
70 lines (66 loc) · 2.16 KB
/

028_Implement_strStr().py

Copy path

File metadata and controls

70 lines (66 loc) · 2.16 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution(object):
# def strStr(self, haystack, needle):
# """
# :type haystack: str
# :type needle: str
# :rtype: int
# """
# lsh, lsn = len(haystack), len(needle)
# if lsn == 0:
# return 0
# pos, index = 0, 0
# while index <= lsh - lsn:
# if haystack[index] == needle[pos]:
# backup = index
# while index < lsh and pos < lsn and haystack[index] == needle[pos]:
# pos += 1
# index += 1
# if pos == len(needle):
# return index - pos
# index = backup
# index += 1
# pos = 0
# return -1
# def strStr(self, haystack, needle):
# lsh, lsn = len(haystack), len(needle)
# if lsn == 0:
# return 0
# pos, index = 0, 0
# while index <= lsh - lsn:
# if haystack[index] == needle[0]:
# # slice index:index + lsn
# if haystack[index:index + lsn] == needle:
# return index
# index += 1
# return -1
# KMP
# https://discuss.leetcode.com/topic/3576/accepted-kmp-solution-in-java-for-reference/2
def strStr(self, haystack, needle):
lsh, lsn = len(haystack), len(needle)
if lsn == 0:
return 0
next = self.makeNext(needle)
i = j = 0
while i < lsh:
if j == -1 or haystack[i] == needle[j]:
i += 1
j += 1
if j == lsn:
return i - lsn
if i < lsh and haystack[i] != needle[j]:
j = next[j]
return -1
def makeNext(self, needle):
ls = len(needle)
next = [0] * ls
next[0], i, j = -1, 0, -1
while i < ls - 1:
if j == -1 or needle[i] == needle[j]:
next[i + 1] = j + 1
if needle[i + 1] == needle[j + 1]:
next[i + 1] = next[j + 1]
i += 1
j += 1
if needle[i] != needle[j]:
j = next[j]
return next
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.