题目来源:

  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

相关文章:

  • 2021-12-16
  • 2021-12-05
  • 2021-07-18
  • 2021-06-28
  • 2022-01-15
  • 2021-08-21
猜你喜欢
  • 2021-12-30
  • 2021-10-05
  • 2022-12-23
  • 2021-09-10
  • 2021-12-10
  • 2021-06-10
  • 2021-08-06
相关资源
相似解决方案