LeetCode--028--实现strSTR()

 

问题描述:spa

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

示例 1:blog

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

示例 2:字符串

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

方法1:直接用find方法io

 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:用截取靶串的方式作对比class

 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:11object

相关文章
相关标签/搜索