字符串匹配 我的方法 vs KMP算法(看不懂)

示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1

我的方法:
class Solution {
public:
    int strStr(string haystack, string needle) {
        int hay_size=haystack.size();
        int nee_size=needle.size();
        if(nee_size==0){
            return 0;
        }
        if(hay_size<nee_size){
            return -1;
        }
        
        int h=0;
        int mark=0;
        int n=0;
        for(int h=0;h<hay_size;h++){
            if(haystack[h]==needle[n]){
                mark=h;
                for(n=0;n<nee_size;n++){
                    if(needle[n]!=haystack[h]){
                        break;
                    }
                    if((n==nee_size-1&&h==hay_size-1)||(n==nee_size-1&&h<hay_size-1)){
                        return mark;
                    }
                    if(h==hay_size-1&&n!=nee_size-1){
                        return -1;
                    }
                    
                    h++;   
                }
                h=mark;
                n=0;
            }
        }
        return -1;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。