Вот формулировка проблемы/ссылка:
- Найдите индекс первого вхождения в строку
Пример 1:
Ввод: haystack = "sadbutsad", Needle = "sad"
Вывод: 0
Объяснение: слово "sad" встречается в индексах 0 и 6.
Первое вхождение находится в индексе 0, поэтому мы возвращает 0.
Пример 2:
Ввод: haystack = "leetcode", Needle = "leeto"
Вывод: -1Объяснение: «leeto» не встречается в «leetcode», поэтому мы возвращаем -1.
МОЙ КОД
`
Код: Выделить всё
public int StrStr(string haystack, string needle)
{
if (needle == haystack)
{
return 0;
}
if (needle.Count() > haystack.Count())
{
return -1;
}
int currentIndex = 0;
int i = 0;
int target = needle.Count();
int seeIfAtTarget = 0;
string tempString = needle;
//goes through the main word
foreach (char letterInMainWord in haystack)
{ //if the letter is the same as the first letter of the comparison
if (letterInMainWord == needle[0])
{
currentIndex = i;
//loops through the letters in the compared word
foreach (char letter in tempString)
{ //adds one to seeIfAtTarget, and we will check to see if that meets the target
if (letter == haystack[currentIndex])
{
seeIfAtTarget++;
currentIndex++;
}
else
{
seeIfAtTarget = 0;
break;
}
if (seeIfAtTarget == target)
{
return i;
}
}
}
i++;
}
return -1;
}
Я пробовал использовать отладку по точкам останова и списки наблюдения в VS, а также пробовал использовать AI
Подробнее здесь: https://stackoverflow.com/questions/785 ... ted-for-al