C# 写 LeetCode easy #28 Implement strStr()

2八、Implement strStr()this

Implement strStr().spa

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

Example 1:blog

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:字符串

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

Clarification:string

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

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().io

 

代码class

static void Main(string[] args)
        {
            var haystack = "hello";
            var needle = "ll";

            var res = ImplementstrStr(haystack, needle);
            Console.WriteLine(res);
            Console.ReadKey();
        }

        private static int ImplementstrStr(string haystack, string needle)
        {
            var match = true;
            for (var i = 0; i <= haystack.Length - needle.Length; i++)
            {
                match = true;
                for (var j = 0; j < needle.Length; j++)
                {
                    if (haystack[i + j] != needle[j])
                    {
                        match = false;
                        break;
                    }
                }
                if (match) return i;
            }
            return -1;

 

解析变量

输入:字符串

输出:匹配位置

思想:定义一个匹配变量match,从首字母循环,使用内循环逐一判断是否每一个字母都能匹配,若不匹配马上退出内循环。

时间复杂度:O(m*n)  m和n分别是两个字符串长度。

相关文章
相关标签/搜索