Topic links
https://leetcode.com/problems/implement-strstr/
Original title
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Topic translation
Implement the STRSTR () function. This function is used to determine whether a string needle is a substring of another string haystack. If it is, the function returns the address that needle first appeared in Haystack; otherwise, 1 is returned.
Method of ThinkingIdea one
Since it is required to implement the STRSTR function, then the library function String.find () is not appropriate ... Although not suitable, also put here for reference.
Code
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ return haystack.find(needle)
Idea two
Scan haystack, when encountering the same position as the needle first character, check that the haystack starts at that location with the same length as the needle, and needle is the same.
Code
class solution(object): def strStr(self, haystack, needle): "" : Type Haystack:str:type needle:str:rtype:int "" " if notNeedlereturn 0 forIinchXrange (Len (haystack)-Len (needle) +1):ifHaystack[i] = = needle[0]: j =1 whileJ < Len (needle) andHAYSTACK[I+J] = = Needle[j]: j + =1 ifj = = Len (needle):returnIreturn-1
Three Ideas
Simplify the above code with a similar substring approach.
Code
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ forin1): if haystack[i:i+len(needle)] == needle: return i return -1
Idea four
Since this is a pattern matching problem, we can consider the KMP algorithm. The algorithm can complete matching lookups (O (n+m)) in linear time for any pattern and target sequence without degradation. This is no longer about the principle of the algorithm, only implemented code.
Code
class solution(object): def strStr(self, haystack, needle): "" : Type Haystack:str:type needle:str:rtype:int "" " if notNeedlereturn 0 #generate next array, need O (n) timeI, J, m, n =-1,0, Len (haystack), Len (needle) next = [-1] * N whileJ < N-1:#needle [K] stands for prefix, neelde[j] stands for postfix ifi = =-1 orNeedle[i] = = Needle[j]: I, j = i +1, J +1NEXT[J] = iElse: i = next[i]#check through the haystack using next, Need O (m) timei = j =0 whileI < M andJ < n:ifj = =-1 orHaystack[i] = = Needle[j]: I, j = i +1, J +1 Else: j = next[j]ifj = = N:returnI-jreturn-1
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51708389
Implement strStr () [Easy] (Python)