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

相關文章
相關標籤/搜索