lintcode-easy-strStr

For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return -1.

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

 

class Solution {
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        //write your code here
        if(source == null || target == null)
            return -1;
        
        if(source.length() == 0 && target.length() == 0)
            return 0;
        if(target.length() == 0)
            return 0;
        
        int size1 = source.length();
        int size2 = target.length();
        
        if(size1 < size2)
            return -1;
        
        for(int i = 0; i <= size1 - size2; i++){
            if(source.charAt(i) == target.charAt(0)){
                int j = 0;
                for(; j < size2; j++){
                    if(source.charAt(i + j) != target.charAt(j))
                        break;
                }
                if(j == size2)
                    return i;
            }
        }
        
        return -1;
    }
}

 

posted @ 2016-03-11 07:50  哥布林工程师  阅读(117)  评论(0编辑  收藏  举报