Question: http://oj.leetcode.com/problems/implement-strstr/
Question Name: Implement strStr()
The KMP is a much better solution. But as long as brute force passed all tests, let’s use brute force.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution: # @param haystack, a string # @param needle, a string # @return a string or None def strStr(self, haystack, needle): # Hanlde two special cases. if needle == "": return haystack if haystack == "": return None lenHaystack = len(haystack) lenNeedle = len(needle) begin = 0 # Compare each substring as long as their length # is >= the length of needle while lenHaystack - begin >= lenNeedle: for index in xrange(lenNeedle): if haystack[begin+index] != needle[index]: # Find a different char break else: # Completely the same return haystack[begin:] begin += 1 return None |
This code has a bug
Could you please provide more details about the
bug
? Thanks!…also thank you for this website, it’s been helpful