Tuesday, March 22, 2016

[LeetCode] 28. Implement strStr()


Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
1. Brute Force.
public class Solution {
    public int strStr(String haystack, String needle) {
        int lenH = haystack.length();
        int lenN = needle.length();
        
        if(0 == lenH){
            if(0 == lenN){
                return 0;
            }else{
                return -1;
            }
        }
        
        // error: i < lenH - lenN 
        for(int i = 0; i < lenH - lenN +1 ; ++i){
            boolean match = true;
            
            // error: indexing error multiple times
            for(int j = 0; j < lenN; ++j){
                if(haystack.charAt(i + j) != needle.charAt(j)){
                    match = false;
                    break;
                }
            }
            if(match){
                return i;
            }
        }
        return -1;
    }
}


2. KMP algorithm. Laters.

No comments:

Post a Comment