28. Implement strStr()

第一次提交

int strStr(char* haystack, char* needle)
{
    int length1 = strlen(haystack);
    int length2 = strlen(needle);
    int i = 0;
    int j = 0;
    int index = 0;
    int tempi = 0;
    int tempj = 0;
    if(length2 == 0)
    {
        return 0;
    }
    for(;i < length1;i ++)
    {
        if(j < length2)
        {
            if(haystack[i] == needle[j])
            {
                index = i;
                tempi = i;
                while(i < length1 && j < length2)
                {
                    if(haystack[i] != needle[j])
                    {
                        break;
                    }
                    if(j == length2 - 1)
                    {
                        return index;
                    }
                    i++;
                    j++;
                }
                i = tempi;
                index = 0;
                j = 0;
            }
        }
    }
    return -1;
}

虽然提交通过了,但是运行时间实在是惨不忍睹。

在网上参考了其他人的代码后,运行时间大大提升

int strStr(char* haystack, char* needle)
{
    int length1 = strlen(haystack);
    int length2 = strlen(needle);
    int j;
    for(int i = 0;i <= length1 - length2;i ++)
    {

        for(j = 0;j < length2;j ++)
        {
            if(haystack[i+j] != needle[j])
            {
                break;
            }
        }
        if(j == length2)
        {
            return i;
        }

    }
    return -1;
}

注意

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

LeetCode这里提示,要考虑needle为空时的情况,这在面试时是一个好的问题。
另外的解法:标准KMP算法
日后填坑
参考资料:
1 https://www.cnblogs.com/ganganloveu/p/3753981.html
2 https://blog.csdn.net/v_july_v/article/details/7041827

posted @ 2019-03-07 21:55  尚修能的技术博客  阅读(169)  评论(0编辑  收藏  举报