争取每周做五个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;
}
网友评论