###### tags: `LeetCode`,`Java`,`Easy` # Easy-28. Find the Index of the First Occurrence in a String ### **題目連結:** [**Find the Index of the First Occurrence in a String**](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/) ### **解題方向** * 使用一個 for 迴圈從 haystack 的開頭開始逐一搜尋,每次搜尋 needle 的長度。 * 在搜尋前,先檢查是否已超出 haystack 的範圍,若是,直接回傳 -1。 * 若還在 haystack 的範圍內,則使用 substring() 方法來取得當前搜尋位置及其後 needle 長度的子字串,並與 needle 比對是否相同。 * 如果相同,回傳當前搜尋位置;否則,繼續搜尋。 * 若整個 haystack 都搜尋完畢都找不到相符的子字串,回傳 -1。 ### **完整程式碼** ```java= class Solution { public int strStr(String haystack, String needle) { for(int i=0;i<haystack.length();i++){ if(i+needle.length()>haystack.length()){ return -1; }else if(haystack.substring(i,i+needle.length()).equals(needle)){ return i; } } return -1; } } ```