【LeetCode】28 . 找出字符串中第一个匹配项的下标

28 . 找出字符串中第一个匹配项的下标(简单)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法:双指针法

思路

  • 使用 find 函数枚举原串 ss 中的每个字符作为「发起点」,每次从原串的「发起点」和匹配串的「首位」开始尝试匹配:

    匹配成功:返回本次匹配的原串「发起点」。
    匹配失败:枚举原串的下一个「发起点」,重新尝试匹配。

代码

class Solution {
    
    
public:
    int strStr(string haystack, string needle) {
    
    
        int pos = haystack.find(needle[0]);
        while(pos != -1) {
    
    
            int p = pos, q = 0;
            while(q<needle.size() && haystack[p] == needle[q]){
    
    
                p++, q++;
            }
            // 已经将needle遍历完毕,说明匹配成功
            if(q == needle.size()) return pos;
            else {
    
    
                // 将先前匹配的字符置'0',防止重复匹配
                haystack[pos] = '0';
                // 寻找下一个可能匹配的位置
                pos = haystack.find(needle[0]);
            }
        }
        return pos;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43894455/article/details/132544540