28. 实现 strStr()

1.题目描述

实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
在这里插入图片描述
示例 2:
在这里插入图片描述
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

2.方法1

最直接的方法 - 沿着字符串逐步移动滑动窗口,将窗口内的子串与 needle 字符串比较。
在这里插入图片描述

3.代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), L = needle.size();
        for(int start = 0; start < n - L + 1; ++start){
            if(haystack.substr(start, L) == needle){
                return start;
            }
        }
        return -1;
    }
};

4.复杂度分析

时间复杂度:O((N−L)L),其中 N 为 haystack 字符串的长度,L 为 needle 字符串的长度。内循环中比较字符串的复杂度为 L,总共需要比较 (N - L) 次。
空间复杂度:O(1)。

5.方法2

Sunday 匹配机制:
1.目标字符串String
2.模式串 Pattern
3.当前查询索引 idx (初始为 0)
4.待匹配字符串 str_cut : String [ idx : idx + len(Pattern) ]
每次匹配都会从 目标字符串中 提取 待匹配字符串与 模式串 进行匹配:
1.若匹配,则返回当前 idx
2.不匹配,则查看 待匹配字符串 的后一位字符 c:
(1)若c存在于Pattern中,则 idx = idx + 偏移表[c]
(2)否则,idx = idx + len(pattern)
Repeat Loop 直到 idx + len(pattern) > len(String)

6.代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        int hSize = haystack.size();
        int nSize = needle.size();
        unordered_map<char, int> bias;
        for(int i = 0;i < needle.size();++i){
            bias[needle[i]] = nSize - i;
        }
        int i = 0;
        while(i <= hSize - nSize){
            if(haystack.substr(i, nSize) == needle){
                return i;
            }
            else{
                if(i + nSize > hSize - 1){
                    return -1;
                }
                else{
                    if(bias.find(haystack[i + nSize]) != bias.end()){//窗口后一个字符串是否在模式中
                        i += bias[haystack[i + nSize]];
                    }
                    else{
                        i += nSize + 1;
                    }
                }
            }
        }
        return -1;
    }
};

7.复杂度分析

时间复杂度:最坏情况:O(nm) 平均情况:O(n)
空间复杂度:O(m)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值