LeetCode - 实现strStr()

题目描述

实现str()函数。

给定一个haystack字符串和一个needle字符串,在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1。

示例

输入: haystack = "hello", needle = "ll"
输出: 2

我的思路

以haystack字符串为主,遍历haysack字符串分别以每个字符串为起点,嵌套遍历needle字符串,时间复杂度为O(m*n)。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size();
        int m = needle.size();
        if(needle.empty()){
            return 0;
        }
        int i = 0;
        int j = 0;
        for(i=0;i<=n-m;i++){ 
            bool flag = true;
            for(j=0;j<m;j++){
                if(haystack[i+j] != needle[j]){
                    flag = false;
                    break;
                }
            }  
        if(flag) return i;
        }
    return -1;
    }
};

更好的思路

可以考虑到灵活地使用substr函数,同样遍历haysack字符串分别以每个字符串为起点,截取needle大小的一段字符串分别与neddle字符串比较,减少了遍历neddle每一个字符串所花费的时间,时间复杂度O(n-m+1)。

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

还有一种rolling hash的算法可以实现O(n)的时间复杂度具体参考rolling hash-Wikipedia

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值