From 4d27998e6ba798c66a949351572b1a291f14bccb Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 18 Dec 2024 04:32:46 -0600 Subject: [PATCH] adding find index first occurrence --- .../find_index_first_occurrence.py | 14 ++++++++++++++ ...test_find_index_first_occurrence_round_12.py | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_12/find_index_first_occurrence.py create mode 100644 tests/test_150_questions_round_12/test_find_index_first_occurrence_round_12.py diff --git a/src/my_project/interviews/top_150_questions_round_12/find_index_first_occurrence.py b/src/my_project/interviews/top_150_questions_round_12/find_index_first_occurrence.py new file mode 100644 index 00000000..55464b91 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_12/find_index_first_occurrence.py @@ -0,0 +1,14 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + + len_needle = len(needle) + len_haystack = len(haystack) + + for i in range(len_haystack - len_needle + 1): + if haystack[i:i+len_needle] == needle: + return i + + return -1 \ No newline at end of file diff --git a/tests/test_150_questions_round_12/test_find_index_first_occurrence_round_12.py b/tests/test_150_questions_round_12/test_find_index_first_occurrence_round_12.py new file mode 100644 index 00000000..b855c534 --- /dev/null +++ b/tests/test_150_questions_round_12/test_find_index_first_occurrence_round_12.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_12\ +.find_index_first_occurrence import Solution + +class FirstOccurrenceIndex(unittest.TestCase): + + def test_first_occurrence_index(self): + solution = Solution() + output = solution.strStr(haystack="sadbutsad", needle="sad") + target = 0 + self.assertEqual(output, target) + + def test_no_first_occurrence_index(self): + solution = Solution() + output = solution.strStr(haystack="leetcode", needle="leeto") + target = -1 + self.assertEqual(output, target) \ No newline at end of file