【LEET-CODE】28. Implement strStr()

本文介绍了一种使用C++实现strStr()函数的方法,该函数用于查找子串在主串中首次出现的位置。通过遍历主串并与子串进行逐个字符的比较,实现了高效的子串搜索。

Question:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:

返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。 

利用substr依次比较,没什么说的。

注意substr(i,n)的含义是返回一个 从string[i]开始取长度为n 的string类型变量,而不是从i到n,之前理解有误。


Code:

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


竟然打败95%,庆祝一下。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值