lintcode 28. Implement strStr()

lintcode 28. Implement strStr()_第1张图片
image.png
class Solution {
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    int strStr(const char *source, const char *target) {
        // write your code here
        //if(!source && !target) return 0;
        
        if(!source || !target) return -1;
        if(strlen(target) == 0 ) return 0;
        for(int i = 0; i < strlen(source); i++){
            if(source[i] != target[0]){
                continue;
            }
            int j = 1;
            for(;j < strlen(target); j++){
                if(source[i+j] != target[j]){
                    break;
                }
            }
            if(j == strlen(target)){
                return i;
            }
        }
        return -1;
    }
};

你可能感兴趣的:(lintcode 28. Implement strStr())