Implement strStr() or indexOf() Java Solution - The Coding Shala

Home >> Interview Questions >> Implement strStr()

Implement strStr() or indexOf() Java Solution


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

Example 1:

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

Example 2:

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

Implement strStr() or indexOf() Java Solution

If the needle char does not match with haystack return -1 else continue checking.


class Solution {
    public int strStr(String haystack, String needle) {
        int len1 = haystack.length();
        int len2 = needle.length();
        if(len2 == 0) return 0;
        int index = -1;
        if(len2>len1) return -1;
        for(int i=0; i<len1; i++){
            int flag=0;
            if(haystack.charAt(i) == needle.charAt(0)){
                int tmp = i;
                int cnt = 0;
                while(tmp < len1 && cnt<len2){
                if(flag==0 && cnt==len2) { index = i; break;} 
        return index;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala