TGViewer
C/C++ | LeetCode C/C++ | LeetCode @easy_c_plus_task · 3.23K subscribers
Post #1926 310
Задача: №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 длиннее haystack, возвращаем -1.

2⃣Если строки равны по длине, сравниваем напрямую.

3⃣Иначе перебираем haystack, берём подстроку длины needle и сравниваем с needle.

😎 Решение:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() < needle.size()) return -1;
if(haystack.size() == needle.size()) {
if(haystack == needle) return 0;
else return -1;
}
for(int i = 0; i <= haystack.size() - needle.size(); i++) {
string s = haystack.substr(i, needle.size());
if(s == needle) {
return i;
}
}
return -1;
}
};


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_plus_task
  1. Oct 13, 2026Задача: 647. Palindromic Substrings Сложность: medium Если задана строка s, верните количе…
  2. Oct 11, 2026Задача: 37. Sudoku Solver Сложность: hard Напишите программу, которая решает судоку, запол…
  3. Oct 9, 2026Задача: 33. Search in Rotated Sorted Array Сложность: medium Дан массив nums, отсортирован…
  4. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для C/C++ разработчика, которые нигде больше не пу…
  5. Oct 5, 2026Задача: 40. Combination Sum II Сложность: medium Дан массив candidates и число target. Най…
  6. Oct 5, 2026Задача: 1014. Best Sightseeing Pair Сложность: easy Вам дан целочисленный массив values, в…
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 →