TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.44K subscribers
Post #1733 590
Задача: №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⃣Проверить граничный случай: если needle пустая — вернуть 0.

2⃣Построить функцию сбоев (prefix function) для строки needle по алгоритму Кнута-Морриса-Пратта (КМП), чтобы ускорить поиск.

3⃣Пройти по строке haystack и при совпадении символов с needle — продвигать указатель. Если несовпадение — использовать функцию сбоев для эффективного сдвига.

😎 Решение:
public class Solution {

private int[] failureFunction(char[] str) {
int[] f = new int[str.length + 1];
for (int i = 2; i < f.length; i++) {
int j = f[i - 1];
while (j > 0 && str[j] != str[i - 1]) j = f[j];
if (j > 0 || str[j] == str[i - 1]) f[i] = j + 1;
}
return f;
}

public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
if (needle.length() <= haystack.length()) {
int[] f = failureFunction(needle.toCharArray());
int i = 0, j = 0;
while (i < haystack.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++; j++;
if (j == needle.length()) return i - j;
} else if (j > 0) {
j = f[j];
} else {
i++;
}
}
}
return -1;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 14, 2026Post #2298
  2. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
  3. Oct 13, 2026Post #2296
  4. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  5. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
  6. Oct 11, 2026Задача: 672. Bulb Switcher II Сложность: medium Есть комната с 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 →