您好,欢迎来到花图问答。
搜索
您的当前位置:首页Oct-18-2018

Oct-18-2018

来源:花图问答

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

Title:

Description:

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;
        }

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务