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

Pranjit MedhiPranjit Medhi
1 min read

Question Statement: 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.

Solution:
To solve this question we have to take the substring of haystack and find if the needle string is present in the haystack

Edge cases to consider

  1. When the anyone of the needle or the haystack strings are empty . We should return -1;

  2. When the length of hackstack is lesss than the length of needle. we should return -1;

My Solution:

   public int strStr(String haystack, String needle) {
        int hayLen = haystack.length() , needLen =  needle.length();
        if( hayLen == 0 || needLen  == 0 )
        {
            return -1;
        }
        if(hayLen < needLen)
        {
            return -1;
        }
        for(int i = 0; i < hayLen - needLen +1 ; i++)
        {
            if(haystack.substring(i, i+needle.length()).equals(needle))
            {
                return i;
            }
         }
         return -1;
    }

Please let me know if you could come up with a better solution for this problem.

0
Subscribe to my newsletter

Read articles from Pranjit Medhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pranjit Medhi
Pranjit Medhi