Implement strStr()
Question
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Tags
- String
- Two Pointers
Thought
Use the brute force search algorithm.
Code
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(haystack) < len(needle):
return -1
if needle == '':
return 0
for i in xrange(len(haystack) - len(needle) + 1):
if haystack[i] != needle[0]:
continue
j = 0
while j < len(needle):
if haystack[i + j] != needle[j]:
break
j += 1
if j == len(needle):
return i
return -1