LeetCode 筆記 - Implement strStr() Posted on 2022-05-09 實作 C 語言中的 strstr() 函數,尋找子字串出現的起始索引。本文採取直覺且高效的模擬遍歷方式,在 O(N) 複雜度內完成字串匹配。這是一篇掌握基本字串搜尋邏輯與邊界處理的開發隨筆。題目在此 28. Implement strStr()實作 C 語言的 strstr()解題思維不解釋,直接開幹Time complexity: O(n)程式碼1234567891011121314151617class Solution: def strStr(self, haystack: str, needle: str) -> int: if not haystack or not needle: return 0 main_length = len(haystack) check_length = len(needle) if main_length == 1: return 0 for i in range(main_length): if haystack[i:i + check_length] == needle: return i return -1也許你也會想看看LeetCode 筆記 - Count Sorted Vowel StringsLeetCode 筆記 - 97. Interleaving StringLeetCode 筆記 - 18. 4Sum