iT邦幫忙

0

解LeetCode的學習筆記Day28_Find the Index of the First Occurrence in a String

LFI 2025-10-19 21:57:55145 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第二十八天

第二十八題題目:Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

給定兩個字串haystack和needle,回傳needle在haystack中出現的第一個索引,如果不存在則回傳-1

程式碼

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        #return haystack.find(needle)

        result = -1
        for i in range(len(haystack)):
            if haystack[i:i+len(needle)] == needle:
                result = i
                break
        return result

python提供find函數可以直接找到needle出現的第一個索引位置,另一種方式是遍歷hatstack,找i~i+len(needle)長度的字串,相等就代表needle存在於hatstack裡,此時i就等於第一個出現的索引位置。ps:這題太簡單了不多做說明


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言