LeetCode--028--实现strSTR()

 

问题描述:

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

方法1:直接用find方法

 1 class Solution(object):
 2     def strStr(self, haystack, needle):
 3         """
 4         :type haystack: str
 5         :type needle: str
 6         :rtype: int
 7         """
 8         index = haystack.find(needle)
 9         if index >= 0:
10             return index
11         else:
12             return -1

方法2:用截取靶串的方式做对比

 1 class Solution(object):
 2     def strStr(self, haystack, needle):
 3         """
 4         :type haystack: str
 5         :type needle: str
 6         :rtype: int
 7         """
 8         len1=len(haystack)
 9         len2=len(needle)
10         for i in range(len1-len2+1):
11             if haystack[i:i+len2]==needle:
12                 return i
13         return -1

 2018-07-23 18:10:11

posted @ 2018-07-23 18:10  Assange  阅读(277)  评论(0编辑  收藏  举报