#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
28:implement StrStr ()
https://oj.leetcode.com/problems/implement-strstr/
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
===comments by dabay===
Finding substrings in long strings is, of course, the KMP algorithm. Since it's a three-person algorithm, it's definitely not easy. Let's study it when you are empty.
Here is the intuitive solution, traversing the long string, the beginning and the short string of a character to compare, if all are compared, the explanation found.
If the traversal is over, there is no return, the description is not found, return-1.
‘‘‘
Class Solution:
# @param haystack, a string
# @param needle, a string
# @return An integer
def strStr (self, haystack, needle):
i = 0
While I < Len (haystack)-Len (needle) + 1:
M,n = i,0
While n < len (needle) and haystack[m] = = Needle[n]:
M + = 1
n + = 1
if n = = Len (needle):
return I
i + = 1
Else
Return-1
def main ():
Sol = solution ()
Haystack = "Ahi"
needle = "HI"
Print sol.strstr (haystack, needle)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]28:implement strStr ()