首页 > 编程语言 > 详细

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

时间:2015-10-19 22:22:14      阅读:198      评论:0      收藏:0      [点我收藏+]

题目来源:

  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

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

原文:http://www.cnblogs.com/chruny/p/4893126.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!