LeetCode 筆記 - Implement strStr()

實作 C 語言中的 strstr() 函數,尋找子字串出現的起始索引。本文採取直覺且高效的模擬遍歷方式,在 O(N) 複雜度內完成字串匹配。這是一篇掌握基本字串搜尋邏輯與邊界處理的開發隨筆。

發佈
閱讀
約 1 分鐘
字數
146
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

題目在此 28. Implement strStr()

實作 C 語言的 strstr()

解題思維

不解釋,直接開幹

Time complexity: O(n)

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class 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

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟