From f3c627124171abb82da6f032d9dc2cf78284b0bd Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 13 Nov 2024 04:04:16 -0600 Subject: [PATCH] addign index first occurrence algo --- .../first_occurrence_index.py | 14 ++++++++++++++ .../test_first_occurrence_index_round_11.py | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_11/first_occurrence_index.py create mode 100644 tests/test_150_questions_round_11/test_first_occurrence_index_round_11.py diff --git a/src/my_project/interviews/top_150_questions_round_11/first_occurrence_index.py b/src/my_project/interviews/top_150_questions_round_11/first_occurrence_index.py new file mode 100644 index 00000000..c2735d51 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_11/first_occurrence_index.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_11/test_first_occurrence_index_round_11.py b/tests/test_150_questions_round_11/test_first_occurrence_index_round_11.py new file mode 100644 index 00000000..896e8488 --- /dev/null +++ b/tests/test_150_questions_round_11/test_first_occurrence_index_round_11.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_11\ +.first_occurrence_index 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