Simple Java solution


  • 0
    M
    public int strStr(String haystack, String needle) {
            int h = haystack.length();
            int n = needle.length();
    
            // Empty needle matches at first index
            if(n == 0) {
                return 0;
            }
    
            int max = h-n+1;
    
            for(int i = 0; i < max; i++) {
                // Skip if first character does not match
                while(i<max && haystack.charAt(i) != needle.charAt(0)) {
                    i++;
                }
                
                // Once first character matches, match both words by character
                int count = 0, j = 0;
                while(j < n && i < max && needle.charAt(j) == haystack.charAt(i+j)) {
                    count++;
                    j++;
                }
                
                // If all characters in needle match,
                // return the index
                if(count == n) {
                    return i;
                }
            }
            return -1;
        }
    

Log in to reply
 

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