【Leetcode】之Implement strStr()

本文介绍如何实现strStr()函数,用于在主字符串中查找子字符串的首次出现位置。通过双指针法,提高了时间效率。详细解释了程序逻辑,并附上测试通过的代码。

一.问题描述

Implement strStr().

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

二.我的解题思路

这道题目也比较简单,使用简单的双指针比较即可。注意为了提高时间效率,在程序的开头可以对两个字符串的length先进行一个初步的比较。测试通过的程序如下所示:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len=haystack.length();int candidate=-1;
        int need = 0;int ned_len=needle.length();
        if(len<ned_len) return -1;
        if(len==ned_len)
        {
            for(int i=0;i<len;i++){
            if(haystack[i]!=needle[i]) return -1;
            }
            return 0;
        }

        if(len==0 || ned_len==0) return 0;

        for(int i=0;i<len;i++){
            if(haystack[i]==needle[need]){
                candidate=i;
                while( i<len && need<ned_len){
                    if(haystack[i]!=needle[need]) break;
                    else {i++;need++;}
                }
                if(need==ned_len && (haystack[i-1]==needle[need-1])) return candidate;
                else {
                    need=0;
                    i=candidate;
                    candidate=-1;
                }
            }
        }
        return candidate;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值