代碼思路分析:
1. 邊界情況處理
代碼中沒有顯式處理以下邊界情況,但邏輯已隱含支持:
needle
為空字符串:應返回0
(但題目通常保證needle
非空)。haystack
比needle
短:直接返回-1
(通過循環條件l < n
隱含處理)。
2. 逐個字符匹配
for (int l = 0; l < n; l++) {if (haystack[l] == needle[0]) { // 找到首個字符匹配的位置int r = 0;int res = l; // 記錄起始位置while (r < needle.size() && haystack[l] == needle[r]) {l++;r++;}// ...}
}
- 外層循環:遍歷
haystack
的每個字符haystack[l]
。 - 內層循環:當
haystack[l]
與needle
的首字符匹配時,嘗試匹配整個needle
。r
表示當前匹配到needle
的位置。res
記錄needle
在haystack
中的起始位置。
3. 匹配成功判斷
if (r == needle.size()) {return res; // 完全匹配,返回起始位置
}
- 如果
r
達到needle
的長度,說明完全匹配,返回起始位置res
。
class Solution {
public:int strStr(string haystack, string needle) {int n=haystack.size();for(int l=0;l<n;l++){if(haystack[l]==needle[0]){int r=0;int res=l;while(r<needle.size()&&haystack[l]==needle[r]){l++;r++;}if(r==needle.size()){return res; }l=res;}}return -1;}
};