LeetCode题解——实现 strStr()

LeetCode题解——实现 strStr()

  • 题目介绍

  • 解题思路
  1. 方法一:用c++自带的find函数可以很容易解决,但是明显违背了题目的意愿
  2. 方法二:遍历haystack,当haystack的当前字符haystack[index]与needle的首字符一样,就进入while循环比对后面的
  3. 当相同字符的长度等于needle的长度,说明needle是haystack的子串,返回i-needle长度,即是needle在haystack中的下标位置
  4. 如果相同字符的长度不等于needle的长度,说明不是子串,继续从刚刚出现首字符相同位置haystack[index]的下一个位置haystack[index+1]继续遍历
  • 代码示例
class Solution {
public:
    int strStr(string haystack, string needle) {
        int len = haystack.length();
        int dstLen = needle.length();
        if(dstLen == 0) {
            return 0;
        }
        if(len == 0) {
            return -1;
        }
        int res = -1;
        int index = -1;
        for(int i = 0; i < len; i++) {
            int j = 0;
            int count = 0;
            if(haystack[i] == needle[j]){
                index = i;
            }
            cout<<"i = "<<i<<endl;
            while(haystack[i] == needle[j] && j<dstLen) {
                i++;
                j++;
                count++;
            }
            if(count == dstLen){
                res = i-dstLen;
                break;
            }
            if(index != -1) {
                i = index;
                index = -1;
            }  
        }
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值