C# 写 LeetCode easy #28 Implement strStr()

时间:2021-01-04 15:56:50

28、Implement strStr()

Implement strStr().

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

Example 1:

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

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -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().

代码:

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 = ; i <= haystack.Length - needle.Length; i++)
{
match = true;
for (var j = ; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
{
match = false;
break;
}
}
if (match) return i;
}
return -;

解析:

输入:字符串

输出:匹配位置

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

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