Java Solution without using IndexOf


  • 0
    X

    The idea is to utilize the length of needle string and do a in-place substring comparison with haystack string.
    Every iteration we do a substring from index i to i+strLen and compare to needle. When we find a match, we return the index in haystack string.
    If no match found at the end, return -1.

    class Solution {
        public int strStr(String haystack, String needle) {
            
            int strLen = needle.length();
            
            if(needle.equals("")){
                return 0;
            }
    
            if(haystack.equals("")){
                return -1;
            }
            
            for(int i=0; i <haystack.length(); i ++){
                if(i+strLen<=haystack.length()){
                    if(haystack.substring(i,i+strLen).equals(needle)){
                        return i;
                    }
                }
      
            }
            return -1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.