admin管理员组

文章数量:1637068

问题描述:
Implement strStr().

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

可能唯一需要注意的是,如果部分满足字符串的要求时,需要将指针回拨到开始满足匹配的下一个再进行。

代码如下:运行时间(0ms)

int strStr(char* haystack, char* needle) {
    int hIndex=0,nIndex=0;  
    int hLength = strlen(haystack);
    int nLength = strlen(needle);
    if(nLength==0)
        return 0;

    int res = -1;
    while(hIndex<hLength&&nIndex<nLength){
        if(haystack[hIndex]==needle[nIndex]){
            if(nIndex==0)
                res = hIndex;
            hIndex++;
            nIndex++;
        }
        else{
            hIndex++;
            nIndex = 0;
            if(res!=-1){
                hIndex = res+1;
                res = -1;
            }
        }
    }
    if(nIndex==nLength)
        return res;
    return -1;
}

本文标签: 语言LeetCodestrStrimplement