
代码思路分析:
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;
}
};