题目:https://www.lintcode.com/prob...
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1

Solution1:暴力移位遍历 O(n^2)

public class Solution {
    /**
     * @param source: 
     * @param target: 
     * @return: return the index
     */
    public int strStr(String source, String target) {
        // Write your code here
        // 注意空字符串处理
        if (source.equals("") == true && target.equals("") == true)
            return 0;
        int i = 0;
        int cur = 0;
        for(; i<source.length(); i++){
            int j = i;
            while(j < source.length() && cur < target.length() && source.charAt(j) == target.charAt(cur)) {
                j++;
                cur++;

            }
            if(cur == target.length()) return i;
            else if (j == source.length()) return -1;
            else{
                cur = 0;
            }
        }
        return -1;
    }
}

Solutuion2: 字符串查找之 Rabin Karp 算法(!哈希算法的运用) 利用Hash算法将字符串映射成数字,比较哈希值,哈希值相同时再比较String。O(m+n)

public class Solution {
    /**
     * @param source: 
     * @param target: 
     * @return: return the index
     */
    public int strStr(String source, String target) {
        // Write your code here
        int base = 31;
        int range = 1000000;
        int targethash = 0;
        int sourcehash = 0;
        int power = 1;

        if(target.equals("") == true)//!注意错误:特殊情况处理
            return 0;

        if(source.equals("") == true || target.length() > source.length())//!注意错误:特殊情况处理
            return -1;

        for(int i=0; i < target.length(); i++){
            targethash = (targethash * base + target.charAt(i)) % range; //!注意错误:% range
            sourcehash = (sourcehash * base + source.charAt(i)) % range; //!注意错误:% range
            power = (power * 31) % range; //!注意错误:% range
        }


        for(int j = target.length(); j <= source.length(); j++){
            if(sourcehash == targethash){
               String substr = source.substring(j - target.length(), j);
               if(substr.equals(target)) return j - target.length();
            }else if(j == source.length()){
                return -1;
            }else{
                sourcehash = (sourcehash * base + source.charAt(j)) % range - source.charAt(j - target.length()) * power % range ;
                if(sourcehash < 0) sourcehash = sourcehash + range;
            }

        }
        return -1;
    }
}

Solution3: KMP 算法


swan
16 声望0 粉丝