MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / strStr

Method strStr

String/ImplementStrStr().py:43–72  ·  view source on GitHub ↗

:type haystack: str :type needle: str :rtype: int

(self, haystack, needle)

Source from the content-addressed store, hash-verified

41"""
42class Solution(object):
43 def strStr(self, haystack, needle):
44 """
45 :type haystack: str
46 :type needle: str
47 :rtype: int
48 """
49 # bulit-in 20ms
50 # return haystack.find(needle)
51
52 # myself
53 if not needle:
54 return 0
55
56 # 24ms.
57 lengthHaystack = len(haystack)
58 lengthNeedle = len(needle)
59
60 if lengthNeedle > lengthHaystack:
61 return -1
62
63 if lengthNeedle == lengthHaystack:
64 return 0 if haystack == needle else -1
65
66 for i, d in enumerate(haystack):
67 if lengthHaystack - i < lengthNeedle:
68 return -1
69
70 if d == needle[0]:
71 if haystack[i:i+lengthNeedle] == needle:
72 return i
73

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected