今天下大雨我的褲子和鞋子都濕掉了...超不舒服><
再不爽都要來寫今天的題目,題目大意是: 在字串 haystack 中找出 needle 第一次出現的位置索引,若找不到回傳 -1。若 needle 是空字串,回傳 0(這是題目要求的特例)
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0; //特殊情況:如果 needle 是 null、或長度為 0,題目規定要回傳 0。
}
int n = haystack.length();
int m = needle.length();
if (m > n) {
return -1; //如果 needle 比 haystack 還長,就不可能找到,直接回 -1
}
for (int i = 0; i <= n - m; i++) {
// 我們只需要從 0 才到 n-m(包含),因為若起始位置超過 n-m,從那裡開始剩下的字元不足以放下整個 needle
int j = 0; //j 是用來遍歷 needle 的索引
while (j < m && haystack.charAt(i + j) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i; // 找到完整配對,回傳起始索引
}
}
return -1; // 都沒找到
}
}