easy 实现 strStr() 双指针 单指针 + 字符串切片

本文探讨了C++中的朴素双指针匹配算法和KMP算法在字符串搜索中的应用,比较了它们的时间复杂度,并介绍了如何通过单指针和Python实现字符串切片简化匹配过程。KMP算法通过预计算『部分匹配表』提高匹配效率,避免回溯操作。
摘要由CSDN通过智能技术生成

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

双指针:

c++

「朴素匹配」而言,一旦匹配失败,将会将原串指针调整至下一个「发起点」,匹配串的指针调整至起始位置,然后重新尝试匹配。「朴素匹配」的复杂度是
O(m*n)


class Solution {
public:
    int strStr(string haystack, string needle) {
        for(int i = 0; i + needle.size() <= haystack.size(); i++) {
            int j = 0;
            while(j < needle.size() && needle[j] == haystack[i + j]){
                 j++;
            }
            if(j == needle.size()){
                return i;
            }
        }
        return -1;
    }
};


单指针 + 字符串切片:

python


class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0

        left=0
        right = len(needle)
        while right <= len(haystack):
            if haystack[left:right] == needle:
                return left
            left += 1
            right += 1

        return -1

c++

c++ string 字符串切片 substr函数:string.substr(pos, n)


class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()){
            return 0;
        }
        
        int left=0;
        int right = needle.size();
        while((left+right) <= haystack.size()){
            if (haystack.substr(left, right) == needle){
                return left;
            }
            left++;
        }
        return -1;
    }
};


KMP 算法

KMP 利用 “已匹配” 部分中相同的「前缀」和「后缀」来加速下一次的匹配。 KMP 的原串指针不会进行回溯(没有朴素匹配中回到下一个「发起点」的过程)

KMP 算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值