[Erlang 學習筆記]Erlang 簡單實現 KMP–字串匹配演算法

來源:互聯網
上載者:User

關於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我,感謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.