Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Implement strStr()

Sharing is caring!

Problem Statement
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Input: haystack = "hello", needle = "ll"
Output: 2
Solution
class Solution {
    public int strStr(String haystack, String needle) {
        char[] source = haystack.toCharArray();
        char[] target = needle.toCharArray();
        
        if (target.length == 0) {
            return 0;
        }
        
        for (int i=0; i<source.length; i++) {
            int t = 0;
            int s = i;
            while (source[s] == target[t] && i+target.length <= source.length) {
                s++;
                t++;
                if (t==target.length) {
                    return i;
                }
            }
        }
        
        return -1;
    }
}