[找出字符串中第一个匹配项的下标]

代码思路分析:

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;
    }
};
相关推荐
武子康2 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
文丑颜不良啊5 小时前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊6 小时前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2521~2540题目解析
java·leetcode
lisw058 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术8 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs10 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575910 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
文丑颜不良啊10 小时前
LeetCode2501~2520题目解析
java·leetcode