iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

LeetCode 每日一題挑戰系列 第 21

Day 21 - Find the Index of the First Occurrence in a String

  • 分享至 

  • xImage
  •  

題目

給定兩個字串 needle 和 haystack,請找出 needle 在 haystack 中第一次出現的位置,並返回該位置的索引值;如果 needle 不存在於 haystack 中,返回 -1。

範例

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" 在索引 0 和 6 出現,但第一次出現在索引 0。

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" 沒有出現在 "leetcode" 中。

解題思路

這題是典型的 字串搜尋 問題,有多種方法:

直接遍歷匹配:用迴圈逐個比對。

KMP 演算法:效率高(O(n+m)),適合長字串搜尋。

Java 自帶方法:haystack.indexOf(needle)。

這裡我們用 最簡單的直接遍歷法,方便理解與實作。

程式碼(Java)
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;

    for (int i = 0; i <= haystack.length() - needle.length(); i++) {
        if (haystack.substring(i, i + needle.length()).equals(needle)) {
            return i;
        }
    }
    return -1;
}

}

心得

這題其實是很基礎的字串搜尋問題,對我來說像是在找一本書裡的關鍵字。
用直接遍歷法最簡單易懂,但效能不是最好。對於競賽或大數據應用,KMP 或 Rabin-Karp 是更好的選擇。
Java 本身有 indexOf,但練習手動實作能幫助理解底層的搜尋邏輯。https://ithelp.ithome.com.tw/upload/images/20250926/20169537KXHdrtnRNT.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537mBPzcWBcyV.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537bF3EraERAJ.png


上一篇
Day 20 - Remove Element
下一篇
Day 22 — Divide Two Integers
系列文
LeetCode 每日一題挑戰25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言