題目
給定兩個字串 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,但練習手動實作能幫助理解底層的搜尋邏輯。