Implement strStr()
The snippet can be accessed without any authentication.
Authored by
Kiryuu Sakuya
Program.cs 1.39 KiB
using System;
using System.Collections.Generic;
namespace test
{
class Program
{
public static int StrStr(string haystack, string needle)
{
bool match = false;
int i = 0;
if (haystack == "" && needle == "")
return 0;
if (haystack != "" && needle == "")
return 0;
if (haystack.Length < needle.Length)
return -1;
for (i = 0; i < haystack.Length; i++)
{
if (match == false)
{
if (haystack[i] != needle[0])
continue;
if (i + needle.Length > haystack.Length)
break;
int j = 0;
while (haystack[i + j] == needle[j])
{
j++;
if (j != needle.Length) continue;
match = true;
break;
}
}
else
break;
}
if (match == true)
{
return i - 1;
}
return -1;
}
public static void Main(string[] args)
{
string a = "mississippi";
string b = "issipi";
Console.WriteLine(StrStr(a, b));
}
}
}
Please register or sign in to comment