美文网首页
Oct-18-2018

Oct-18-2018

作者: 雨生_ | 来源:发表于2018-10-18 22:12 被阅读22次

    争取每周做五个LeedCode题,定期更新,难度由简到难

    Title: Implement strStr()

    Description:

    Implement strStr().

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

    Example:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    Input: haystack = "aaaaa", needle = "bba"
    Output: -1

    Difficulty:

    Easy

    Implement Programming Language:

    C#

    Answer:
    public static int StrStr(string haystack, string needle)
            {
                if (needle == null || needle == string.Empty || haystack == needle)
                    return 0;
    
                if (haystack.Length < needle.Length)
                    return -1;
    
                for (int i = 0; i < haystack.Length; i++)
                {
                    if(haystack[i] == needle[0])
                    {
                        bool flag = true;
                        if (haystack.Length - i < needle.Length)//剩余长度小于比较长度,一定不存在
                            return -1;
                        for (int j = 1; j < needle.Length; j++)
                        {
                            if (haystack[i + j] != needle[j])
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (flag) return i;
                    }
                }
                return -1;
            }
    
    Github

    相关文章

      网友评论

          本文标题:Oct-18-2018

          本文链接:https://www.haomeiwen.com/subject/suxezftx.html