題型解說
這是一題難度為簡單的題目
需要設計一個方法,此方法會傳入兩個字串 haystack 和 needle
確認 needle 是否包含在 haystack 中,如果包含就回傳第一個字元的索引
如果不包含就回傳 -1,如果 needle 是空的就回傳 0
解題思路
這題沒有什麼辦法,只能用簡單的方式來解
利用迴圈找到 haystack 存不存在 needle 的第一個字元
如果存在就利用第二個迴圈一個一個比對,比對成功就回傳索引位置
程式碼
Java
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
class Solution {
public int strStr(String haystack, String needle) {
if ("".equals(needle)) {
return 0;
}
int len1 = haystack.length();
int len2 = needle.length();
if (len2 > len1) {
return -1;
}
if (len2 == len1) {
return haystack.equals(needle)? 0: -1;
}
char first = needle.charAt(0);
// 剩餘字元如果不夠要搜尋的長度就不需要再比對下去了
for (int i = 0, max = len1 - len2; i <= max; i++) {
// 找到符合的第一個字元
if (haystack.charAt(i) != first) {
while (++i <= max && haystack.charAt(i) != first);
}
if (i > max) {
return -1;
}
int j = i + 1;
int end = i + len2;
// 因為第一個字元已經比對完成了,故 k 從 1 開始
for (int k = 1; j < end && haystack.charAt(j) == needle.charAt(k); j++, k++);
if (j == end) {
return i;
}
}
return -1;
}
}