zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    输出控制符的详解
    printf函数的讲解
    关于字节、Ascll码、字符的存储的讲解
    1.2
    1.1
    OS模块学习笔记
    time时间模块总结
    编译py为exe
    python计算excel平均值和标准差
    Python与Excel交互--Xlwings
  • 原文地址:https://www.cnblogs.com/Manual-Linux/p/10492299.html
Copyright © 2011-2022 走看看