给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll" 输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
public class Solution {
public int StrStr(string haystack, string needle) {
int t = 0;
int j = 0;
int i = 0;
if (needle == ""&&haystack!="")
{
t = 0;
}
else if(needle==""&&haystack==""){
t=0;
}
else if(needle!=""&&haystack==""){
t=-1;
}
else
{
for (i = 0; i < haystack.Length; i++)
{
if (j == needle.Length)
{
break;
}
if (needle[0] == haystack[i])
{
if (needle.Length == 1)
{
t = i;
break;
}
else
{
for (j = 1; j < needle.Length; j++)
{
i++;
if (i > haystack.Length - 1)
{
t = -1;
break;
}
else if (needle[j] != haystack[i])
{
i = i - j ;
break;
}
else if (j == needle.Length - 1)
{
t = i - needle.Length + 1;
}
}
}
}
if (i == haystack.Length - 1 && j < needle.Length)
{
t = -1;
}
}
}
return t;
}
}