TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.17K subscribers
Post #1437 355
Задача: 28. Find the Index of the First Occurrence in a String
Сложность: easy

Учитывая две строки needle и haystack, верните индекс первого вхождения needle в haystack или -1, если needle не является частью haystack.

Пример:
Input: haystack = "sadbutsad", needle = "sad"  
Output: 0


👨‍💻 Алгоритм:

1⃣Использовать два указателя i и j для прохода по haystack и needle.

2⃣Применить алгоритм KMP с использованием массива LPS (longest prefix suffix) для оптимального поиска.

3⃣Вернуть индекс первого вхождения needle или -1, если needle не найден.

😎 Решение:
public class Solution {
public int StrStr(string haystack, string needle) {
int i = 0, j = 0;
int[] lps = BuildLPS(needle);

while (i < haystack.Length) {
if (haystack[i] == needle[j]) {
i++;
j++;
if (j == needle.Length) return i - j;
} else {
if (j > 0) j = lps[j - 1];
else i++;
}
}

return -1;
}

private int[] BuildLPS(string needle) {
int[] lps = new int[needle.Length];
int i = 0;

for (int j = 1; j < needle.Length;) {
if (needle[i] == needle[j]) {
lps[j++] = ++i;
} else {
if (i > 0) i = lps[i - 1];
else j++;
}
}

return lps;
}
}


Ставь 👍 и забирай 📚 Базу знаний
  • 🔥 1
More from @easy_c_sharp_task
  1. Oct 16, 2026Задача: 205. Isomorphic Strings Сложность: easy Даны две строки s и t, определите, являютс…
  2. Oct 16, 2026Задача: 1416. Restore The Array Сложность: hard Программа должна была напечатать массив це…
  3. Oct 15, 2026Задача: 217. Contains Duplicate Сложность: easy Дан массив целых чисел nums. Верните true,…
  4. Oct 15, 2026Задача: 759. Employee Free Time Сложность: hard Нам дан список schedule of employees, кото…
  5. Oct 14, 2026Задача: 583. Delete Operation for Two Strings Сложность: medium Даны две строки word1 и wo…
  6. Oct 14, 2026Задача: 1252. Cells with Odd Values in a Matrix Сложность: easy Имеется матрица m x n, кот…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →