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

Home >> Interview Questions >> Implement strStr()

Implement strStr() or indexOf() Java Solution

Problem:



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

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

Java 

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(haystack.charAt(tmp)!=needle.charAt(cnt)){
                        flag=1;
                        break;
                    }  
                    cnt++;
                    tmp++;
                }
                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.

Comments

Popular Posts from this Blog

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

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala