leetcode 28 ---实现strStr()

雨燕双飞 提交于 2020-02-29 15:45:24

题目描述

实现 strStr() 函数。

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

示例 1:

输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:

输入: haystack = “aaaaa”, needle = “bba”
输出: -1

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1 = haystack.size();
        int len2 = needle.size();
        if(len2 == 0)
            return 0;
        int i = 0,j = 0;
        for(i =0;i< len1;i++){
            if(j == len2)
                return i - len2;
            if(haystack[i] == needle[j])
            {
                j++;
            }else {
                i = i - j;
                j = 0;
            }
        }
        if(j == len2){
            return i - len2;
        }
        return -1;
        
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!