Skip to content

Documentation

Source code in find-the-index-of-the-first-occurrence-in-a-string/main.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        """
        Returns the index of the first occurrence of `needle` in `haystack`, or -1 if `needle` is not part of `haystack`.

        Args:
            haystack (str): The string to search within.
            needle (str): The substring to search for.

        Returns:
            int: The index of the first occurrence of `needle` in `haystack`, or -1 if not found.
        """
        n, m = len(haystack), len(needle)
        for i in range(n - m + 1):
            if haystack[i:i+m] == needle:
                return i
        return -1

strStr(haystack, needle)

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Parameters:

Name Type Description Default
haystack str

The string to search within.

required
needle str

The substring to search for.

required

Returns:

Name Type Description
int int

The index of the first occurrence of needle in haystack, or -1 if not found.

Source code in find-the-index-of-the-first-occurrence-in-a-string/main.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def strStr(self, haystack: str, needle: str) -> int:
    """
    Returns the index of the first occurrence of `needle` in `haystack`, or -1 if `needle` is not part of `haystack`.

    Args:
        haystack (str): The string to search within.
        needle (str): The substring to search for.

    Returns:
        int: The index of the first occurrence of `needle` in `haystack`, or -1 if not found.
    """
    n, m = len(haystack), len(needle)
    for i in range(n - m + 1):
        if haystack[i:i+m] == needle:
            return i
    return -1