用 Python 實現 strStr()
假設我們有兩個字串 str 和 sub_str。我們必須找到 sub_str 在 str 中的第一次出現。因此,如果字串 str 是“helloworld”,子串是“lo”,那麼結果將是 3。
這可以透過 C 中的 strstr() 函式來完成。我們必須設計另一個函式,類似於 C 中的 strstr()。
要解決此問題,請按下列步驟操作:
- i := 0,j := 0,m := sub_str 的長度,n := str 的長度
- 如果 m = 0,則返回 0
- 當 i < n 和 n – i + 1 = m 時,執行
- 如果 str[i] = sub_str[j],則
- temp := j
- 當 j < m 和 i < n 並且 sub_str[j] == str[j] 時,執行
- 將 i 和 j 增加 1
- 如果 j = m,則返回 temp
- i := temp + 1
- j := 0
- 否則將 i 增加 1
- 如果 str[i] = sub_str[j],則
- 返回 -1
讓我們看看實現以獲得更好的理解
示例(Python)
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ i = 0 j = 0 m = len(needle) n = len(haystack) if m ==0: return 0 while i<n and n-i+1>=m: if haystack[i] == needle[j]: temp = i while j<m and i<n and needle[j]==haystack[i]: i+=1 j+=1 if j == m: return temp i= temp+1 j = 0 else: i+=1 return -1 haystack = "helloworld" needle = "lo" ob1 = Solution() print(ob1.strStr(haystack, needle))
輸入
haystack = "helloworld" needle = "lo"
輸出
3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP