iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

leetcode系列 第 28

leetcode 28 Find the Index of the First Occurrence in a String

  • 分享至 

  • xImage
  •  

題目
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.
給定兩個字串needle和,傳回在中haystack第一次出現的索引,或如果不是的一部分。needlehaystack-1needlehaystack
解題思路
從母字串的每一個起始位置 i 嘗試比對 needle。

若全部匹配成功 → 回傳 i。

若比對到尾端都沒找到 → 回傳 -1。

時間複雜度:O(n*m)。
https://ithelp.ithome.com.tw/upload/images/20251020/201693406CIp151hD5.png
解題思路
從母字串的每一個起始位置 i 嘗試比對 needle。

若全部匹配成功 → 回傳 i。

若比對到尾端都沒找到 → 回傳 -1。

時間複雜度:O(n*m)。


上一篇
leetcode 27. Remove Element
下一篇
LeetCode 第 29 題:Divide Two Integers
系列文
leetcode30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言