leetcode28实现strStr

一、题目

 

 二、代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.length()==0) return 0;
        if( haystack.length()< needle.length()) return -1;
        int index = 0;
        int start = 0;
        int count = 0;
        while(index<=haystack.length()-needle.length()){
            
            while(index<=haystack.length() && haystack[index]!=needle[0]) index++;
            count = 0;
            start = -1;
            for(int i=index; i<index+needle.length(); i++){
                if(haystack[i] == needle[i-index]){
                    count++;
                }
                else
                    break;
            }
            if(count==needle.length()){
                start = index;
                break;
            }
            else{
                index++;
            }
        }
        if(count != needle.length()) start = -1;
        return start;
    }
};

 

posted @ 2021-12-07 10:56  星光夜  阅读(25)  评论(0编辑  收藏  举报