strstr

N(n*m)的时间复杂度

public class Solution {
public String strStr(String haystack, String needle) {
 
    int nLen = needle.length();
    int hLen = haystack.length();
    
    if(nLen==hLen && nLen==0)
        return "";
    if(nLen == 0)
        return haystack;
    for(int i=0; i<= hLen-nLen; i++){
        int j = 0;
        for( ; j<nLen;j++){
            if(needle.charAt(j)!=haystack.charAt(i+j))break;
        }
        if(j==nLen)
            return haystack.substring(i);
    }
    
    return null;
 
   
}

}

 

kmp:  N(m+n)

http://www.youtube.com/watch?v=iZ93Unvxwtw

 

constructs dfa[][] in time and space to RM.  R is the set of charactor occur. 

 

 

 

package com.kmp;
 
public class KMP {
 
    private String pat;
    private int[][] dfa; //二维字典
     
    public KMP(String pat){
        this.pat = pat;
        int M = pat.length();
        int R = 256;
        //二维字典的构造
        dfa = new int[R][M];
        dfa[pat.charAt(0)][0] = 1;
        for (int X = 0, j = 1; j< M; j++){
            //复制前面某一列的所以跳转,至当前列,这某一列可视为参照列
            for( int c = 0; c < R; c++) dfa[c][j] = dfa[c][X];
            dfa[pat.charAt(j)][j] = j + 1; //第j个字节,刚好在第j个位置上,说明匹配成功
            X = dfa[pat.charAt(j)][X]; //更新参照列的位置
        }
    }
     
    public int find(String content){
        // 查找逻辑,类似游戏
        int i, j;
        int N = content.length();
        int M = pat.length();
        for (i = 0, j = 0; i<N && j<M; i++){
            j = dfa[pat.charAt(i)][j];
        }
        if (j == M) return i - M; //找到
        else return M;
    }
 
}

 

转载于:https://www.cnblogs.com/leetcode/p/4005042.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值