關於KMP演算法的概念,大家應該都知道的了,具體可以參看wiki,研究研究,或google瞭解。。。。。。
不說廢話,上代碼 =。=
%%%-------------------------------------------------------------------%%% @author lqg <>%%% @copyright (C) 2012, lqg%%% @doc%%%%%% @end%%% Created : 26 Jul 2012 by lqg <>%%%--------------------------------------------------------------------module(kmp).%% API-export([patch/2]).-define(Len(X),array:size(X)).-define(Get(X,Y),array:get(X,Y)).-define(Same(X,Y),string:equal(X,Y)).-define(Set(X,Y,Z),array:set(X,Y,Z)).%%% I,Content數組下標%%% J,Keyword數組下標%%% Next,Keyword數組用於回溯的值數組patch(Content,Keyword) -> I=0,J=0, Next = get_next(Keyword), compare(I,J,Content,Keyword,Next).%%% C,Content%%% K,Keyword%%% N,Nextcompare(I,J,C,K,N)-> case I < ?Len(C) oftrue -> case J== -1 oftrue -> I1=I+1,J1=J+1,compare(I1,J1,C,K,N);false -> case ?Same(?Get(I,C),?Get(J,K)) oftrue -> I1=I+1,J1=J+1,case J1==?Len(K) of true ->{true,{I-J,I}}; %%含有關鍵詞,返回關鍵詞範圍 false ->compare(I1,J1,C,K,N)end;false -> J1=?Get(J,N), compare(I,J1,C,K,N) end end;false -> false %%不含關鍵詞 end.%%% K,Keyword%%% H J ,Next數組下標,H<J%%% N, Nextget_next(K)-> H=-1,J=0, N=array:new(array:size(K)), N1=?Set(0,-1,N), get_next(K,N1,H,J).%%% K,Keyword%%% H J ,Next數組下標,H<J%%% N, Nextget_next(K,N,H,J)-> case J < ?Len(K)-1 oftrue-> case H ==-1 oftrue -> J1=J+1,H1=H+1,N1=?Set(J1,H1,N),get_next(K,N1,H1,J1);false -> case ?Same(?Get(J,K),?Get(H,K)) of true->J1=J+1, H1=H+1, N1=?Set(J1,H1,N), get_next(K,N1,H1,J1); false-> H1=?Get(H,N), get_next(K,N,H1,J) end end;false -> N end.
代碼簡單實現了KMP演算法,但是我擔心的是Next[ ]產生的時候會產生過多的記憶體消耗,就是 N1=?Set(J1,H1,N) 這個跌代,但是erlang的工作地方不是記憶體,而是代碼,只要不是atom,沒問題的 。。。。。。
由於對erlang的函數沒太多的使用,可能以上的n行代碼可以用一個函數代替,
由於時間的問題,我沒有深究,如果哪位仁兄又發現,可以call我,感謝!