
代码思路分析:
1. 边界情况处理
代码中没有显式处理以下边界情况,但逻辑已隐含支持:
needle
为空字符串 :应返回0
(但题目通常保证needle
非空)。haystack
比needle
短 :直接返回-1
(通过循环条件l < n
隐含处理)。
2. 逐个字符匹配
cpp
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. 匹配成功判断
cpp
if (r == needle.size()) {
return res; // 完全匹配,返回起始位置
}
- 如果
r
达到needle
的长度,说明完全匹配,返回起始位置res
。
cpp
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;
}
};