leetcode 28. implement-strstr 實現 strStr() python3

時間:2020-6-20

題目地址:https://leetcode-cn.com/problems/implement-strstr

題目難度:Easy

題目描述:

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回  -1。

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。


思路1:暴力破解

代碼段1:一個用例超時

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle: return 0
        if(len(haystack) < (len(needle))): return -1
        temp, index, result = needle[0], 0, []
        for i, x in enumerate(haystack):
            if x == temp:
                result.append(i) 
        print(result) 
        for o in result:
            t, _ = o, True
            for j in needle:
                if t <= len(haystack) - 1:
                    if j == haystack[t]:
                        t += 1
                    else:
                        _ = False
                else:
                        _ = False             
            if(_ == True): 
                return o
        return -1

總結:

  1. 晚上8點寫的,今天出去了一趟,太累了,腦子根本不動,基於測試用例編程,寫了好幾次,明天繼續整吧,思路不清晰的時候果然不能寫代碼

思路2:使用切片

代碼段2:通過

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        L, n = len(needle), len(haystack)
        
        for start in range(n - L + 1):
            if(haystack[start: start + L] == needle):
                return start
        return -1

總結:

  1. 時間複雜度O((N-L)L),將每個長度爲L的同needle進行比較

思路3:使用雙指針

只有和目標串第一位相同的才進行比較

代碼段3:通過

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        L, n = len(needle), len(haystack)
        if L == 0: return 0
        pn = 0
        while pn < n - L + 1:
            while pn < n - L + 1 and haystack[pn] != needle[0]:
                pn += 1
            
            curr_len = pL = 0
            while pL < L and pn < n and haystack[pn] == needle[pL]:
                pn += 1
                pL += 1
                curr_len += 1
            
            if curr_len == L:
                return pn - L
            
            pn = pn - curr_len +1
        return -1

總結:

  1. 時間複雜度O((N-L)L),將每個長度爲L的同needle進行比較

後續優化:KMP算法 

參見:https://leetcode-cn.com/problems/implement-strstr/solution/kmp-suan-fa-xiang-jie-by-labuladong/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章