jinhuang1102

28. Implement strStr()

Oct 22nd, 2018
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. class Solution:
  2.     def strStr(self, haystack, needle):
  3.         """
  4.        :type haystack: str
  5.        :type needle: str
  6.        :rtype: int
  7.        """
  8.         if not needle:
  9.             return 0
  10.        
  11.         m = len(haystack)
  12.         n = len(needle)
  13.        
  14.         if m < n:
  15.             return -1
  16.        
  17.         for i in range(0, m-n+1):
  18.             k = i
  19.             j = 0
  20.             while j < n:
  21.                 if haystack[k] == needle[j]:
  22.                     j = j + 1
  23.                     k = k + 1
  24.                 else:
  25.                     break
  26.                    
  27.             if j == n:
  28.                 return i
  29.        
  30.         return -1
Advertisement
Add Comment
Please, Sign In to add comment