樸素模式匹配演算法java實現

BadRice發表於2016-03-25

對於一個給定的 source 字串和一個 target 字串,你應該在 source 字串中找出 target 字串出現的第一個位置(從0開始)。如果不存在,則返回 -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
        //注意傳入null引數的情況
        if(null == source || null == target ){
            return -1;
        }
        int lenS = source.length();
        int lenT = target.length();
        for (int s = 0; s <= lenS - lenT; s++) {
            boolean sEqual = true;
            int i = 0;
            while(sEqual && i < lenT){
                if(source.charAt(s + i) == target.charAt(i)){
                    i++;
                }else{
                    sEqual = false;
                }
            }
            if(sEqual){
                return s;
            }
        }
        return -1;
    }
}

相關文章