HomeLeetcode28. Find the Index of the First Occurrence in a String -...

28. Find the Index of the First Occurrence in a String – Leetcode Solution

Description:

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.

Examples:

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.

Solution in Python:

Python
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        # Check if needle is an empty string
        if not needle:
            return 0
        
        # Get the length of haystack and needle using the len() function
        len_haystack = len(haystack)
        len_needle = len(needle)
        
        # Iterate through haystack with an index range up to (length of haystack - length of needle + 1)
        # This is because if we start checking beyond this range, there aren't enough characters left
        # in haystack to match the length of needle.
        for i in range(len_haystack - len_needle + 1):
            # Check the substring of haystack from index i to i + length of needle
            if haystack[i:i+len_needle] == needle:
                return i  # Return the starting index if a match is found
        
        # If no match is found after the loop ends, return -1
        return -1

Explanation:

  1. Initial Check for Empty Needle:
    • If needle is an empty string, by definition the function should return 0 since an empty string is always considered to be found at the beginning of any string.
  2. Length Calculation:
    • Calculate the lengths of haystack and needle for convenience.
  3. Iteration Through Haystack:
    • Iterate through haystack from the start to the position where the remaining characters are fewer than the length of needle. This range is calculated as len_haystack - len_needle + 1.
  4. Substring Comparison:
    • For each position i in the calculated range, extract a substring of haystack from i to i + len_needle and compare it with needle.
  5. Return Index or -1:
    • If the substring matches needle, return the current index i.
    • If no match is found after completing the loop, return -1.

Solution in Javascript:

JavaScript
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    // Check if needle is an empty string
    if (!needle.length) {
        return 0;
    }
    
    // Get the lengths of haystack and needle
    const lenHaystack = haystack.length;
    const lenNeedle = needle.length;
    
    // Iterate through haystack with an index range up to (length of haystack - length of needle + 1)
    // This is because if we start checking beyond this range, there aren't enough characters left
    // in haystack to match the length of needle.
    for (let i = 0; i <= lenHaystack - lenNeedle; i++) {
        // Check the substring of haystack from index i to i + length of needle
        if (haystack.substring(i, i + lenNeedle) === needle) {
            return i; // Return the starting index if a match is found
        }
    }
    
    // If no match is found after the loop ends, return -1
    return -1;
};

Solution in Java:

Java
class Solution {
    public int strStr(String haystack, String needle) {
        // Check if needle is an empty string
        if (needle.isEmpty()) {
            return 0;
        }
        
        // Get the lengths of haystack and needle
        int lenHaystack = haystack.length();
        int lenNeedle = needle.length();
        
        // Iterate through haystack with an index range up to (length of haystack - length of needle + 1)
        // This is because if we start checking beyond this range, there aren't enough characters left
        // in haystack to match the length of needle.
        for (int i = 0; i <= lenHaystack - lenNeedle; i++) {
            // Check the substring of haystack from index i to i + length of needle
            if (haystack.substring(i, i + lenNeedle).equals(needle)) {
                return i; // Return the starting index if a match is found
            }
        }
        
        // If no match is found after the loop ends, return -1
        return -1;
    }
}

Solution in C#:

C#
public class Solution {
    public int StrStr(string haystack, string needle) {
        // Check if needle is an empty string
        if (string.IsNullOrEmpty(needle)) {
            return 0;
        }
        
        // Get the lengths of haystack and needle
        int lenHaystack = haystack.Length;
        int lenNeedle = needle.Length;
        
        // Iterate through haystack with an index range up to (length of haystack - length of needle + 1)
        // This is because if we start checking beyond this range, there aren't enough characters left
        // in haystack to match the length of needle.
        for (int i = 0; i <= lenHaystack - lenNeedle; i++) {
            // Check the substring of haystack from index i to i + length of needle
            if (haystack.Substring(i, lenNeedle) == needle) {
                return i; // Return the starting index if a match is found
            }
        }
        
        // If no match is found after the loop ends, return -1
        return -1;
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular