[LeetCode]题解(python):028-Implement strStr()

题目来源:

  https://leetcode.com/problems/implement-strstr/


 

题意分析:

  输入两个字符串haystack和needle,如果needle是haystack的一个子串,那么返回这个子串在haystack出现的第一个位置,否则返回-1.


 

题目思路:

  这个题目是简单题,直接暴力解决就可以了。从i=0出发,如果遇到haystack[i] == needle[0],那么判断从这个出发能不能构成needle,如果可以则返回i。直到i到最后一个字符的长度小于needle的长度。如果前面没有返回值,那么返回-1.时间复杂度是(O((m - n) * n)).


 

代码(python):

  

 1 class Solution(object):
 2     def strStr(self, haystack, needle):
 3         """
 4         :type haystack: str
 5         :type needle: str
 6         :rtype: int
 7         """
 8         size1 = len(haystack)
 9         size2 = len(needle)
10         if size2 == 0:
11             return 0
12         if size1 < size2:
13             return -1
14         i = 0
15         while i < size1:
16             if size1 - i < size2:
17                 return -1
18             if haystack[i] == needle[0]:
19                 j = 1
20                 while j < size2:
21                     if haystack[i + j] != needle[j]:
22                         break
23                     j += 1
24                 if j == size2:
25                     return i
26             i += 1
27         return -1
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4893126.html

posted @ 2015-10-19 21:39  Ry_Chen  阅读(823)  评论(0编辑  收藏  举报