How to ReImplement strStr() in Java

What we want to achieve

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

How to code this

class Solution {
    public int strStr(String haystack, String needle) {
        // If needle is an empty string
        if (needle.isEmpty()) return 0;

        // If the needle is not within the haystack
        if (!haystack.contains(needle)) return -1;

        // declare an index and the needle's length
        int index = 0;
        int len = needle.length();
        
        // loop through the hackstack minus the needle's length
        for (int i = 0; i <= haystack.length() - len; i++) {
            // compare the needle with the hackstack new string
            // created from using substring, start->end
            if (haystack.substring(i, i + len).equals(needle)) {
                // set the index and exit
                index = i;
                break;
            }
        }
        return index;
    }
}
Tags:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments