# 28. Implement strStr()

来源:互联网 发布:linux sftp 默认端口 编辑:程序博客网 时间:2024/06/06 19:04

Implement strStr().

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

class Solution {public:    int strStr(string haystack, string needle) {        int len_1 = haystack.size(),len_2 = needle.size(),j,num=0;        if(needle == "")            return 0;        if(len_1<len_2)            return -1;        for(int i=0;i<len_1-len_2+1;i++){            if(haystack[i]==needle[0]){                num=0;                for(j=0;j<len_2;j++){                    if(haystack[i+j]!=needle[j]){                        break;                    }else{                        num++;                    }                }                if(num==len_2)                    return i;            }        }        return -1;    }};

不是很理解为什么要处理strStr(“”,”“)=0,strStr(“a”,”“)=0的情况,空字符串怎么会有匹配呢?

原创粉丝点击