1. 程式人生 > 其它 >Leetcode - 28. 實現 strStr()

Leetcode - 28. 實現 strStr()

實現strStr()函式。
給你兩個字串haystackneedle,請你在haystack字串中找出needle字串出現的第一個位置(下標從0開始)。如果不存在,則返回-1

說明:
needle是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當needle是空字串時我們應當返回0。這與C語言的strstr()以及JavaindexOf()定義相符。

示例 1:

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

示例 2:

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

示例 3:

輸入:haystack = "", needle = ""
輸出:0

提示:

  • 0 <= haystack.length, needle.length <= 5 * 104
  • haystack 和 needle 僅由小寫英文字元組成

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-strstr
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

解1 2021/8/30 O(?)

def strStr(haystack: str, needle: str) -> int:
    # 實測,str的find,就是這麼返回的
    return haystack.find(needle)

if __name__ == '__main__':
    print(strStr('hello','ll'))
    print(strStr('aaaaa','bba'))
    print(strStr('',''))

說明有比標準庫更快的演算法