less than 1 minute read

28. Find the Index of the First Occurrence in a String

Difficulty: Easy

Related Topics: Two Pointers, String, String Matching

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “sadbutsad”, needle = “sad” Output: 0 Explanation: “sad” occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = “leetcode”, needle = “leeto” Output: -1 Explanation: “leeto” did not occur in “leetcode”, so we return -1.

Code:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        ptr1 = 0
        ptr2 = len(needle)
        word = len(haystack)
        while ptr2 < word+1:
            if haystack[ptr1:ptr2] == needle:
                return ptr1
            else:
                ptr1+=1
                ptr2+=1
        return -1

Feedbacks:

I set two pointers, one as starting index, another one as ending index. So, if haystack[ptr1:ptr2] is same as needle I return ptr1. Else, increment ptr1 and ptr2 by one. Compare them until ptr2 is not larget than haystack length +1. If while loop ends with no return value, I return -1 which means there’s no common prefix.