Find first occurrence of W in S - KMP & BM

1. Problem

Find the start position of first occurrence of String W in String S? (Leetcode Address)

2. Simple Solution

Each round (i from 0 to len(S)-len(W)), start from the ith position and match if the following substring match W or not, if match return i, go to next round( start from i+1 position) if not. Time complexity is O(n*m).
Example:S = "THIS IS A SIMPLE EXAMPLE" W = "EXAMPLE"

Solution:

round 1:

THIS IS A SIMPLE EXAMPLE
EXAMPLE

round 2:

THIS IS A SIMPLE EXAMPLE
 EXAMPLE

......
round 18:

THIS IS A SIMPLE EXAMPLE
                 EXAMPLE

match successful, return position of E (17).

Show me the code (haystack is S, needle is W):

    public int strStr(String haystack, String needle) {
        if(needle.equals("")) return 0;
        if(needle.length() > haystack.length()) return -1;
        for(int i = 0; i < haystack.length(); i ++){
            if(haystack.length() - i < needle.length()) return -1;
            int j = 0;
            while(j < needle.length()){
                if(haystack.charAt(i+j) != needle.charAt(j)) break;
                j ++;
            }
            if(j == needle.length()) return i;
        }
        return -1;
    }

3. KMP Alg.

KMP is the abbr. of Knuth-Morris-Pratt, one of the authors of this algorithm. The other two are Donald Knuth and Vaughan Pratt.

They solve the above problem in a more efficient way. Let's explain it using an example.
The last example is not good enough for explain this algorithm, let's change another one: S = "BBCABCDAB ABCDABCDABDE", W = "ABCDABD"

Solution:

pre-process:(partial match table)
traversal W once (O(m)) we can get table shown below, the 1 under A represents how many char match from the beginning.

A B C D A B D
0 0 0 0 1 2 0

round 1:

BBCABCDAB ABCDABCDABDE
ABCDABD

round 4:

BBCABCDAB ABCDABCDABDE
   ABCDABD

' ' and D not match, and ' ' not part of ABCDABD, so move to the position next to ' '.
round 5:

BBCABCDAB ABCDABCDABDE
          ABCDABD

as can be seen that till D, already 6 chars match, and partial match number is 2, so number of positions to move is num(match) - num(partial match) = (6 -2) = 4. And comparing should start from num(partial match) + 1 = 2 + 1 = 3 after finish moving. Then we get round 11.
round 6:

BBCABCDAB ABCDABCDABDE
              ABCDABD

start comparing from num(partial match) + 1 = 2 + 1 = 3 position of ABCDABD, match successful, return position of first element (10).
As we can see, if use the simple solution, it would take 15 rounds to find the position, but with KMP it only takes 6 round to find it.

Time Complexity:
table algorithm is O(k), where k is the length of W. the traversal algorithm is O(n), where n is the length of S. so the time complexity of the whole algorithm is O(k+n).

Show me the code!

public static int kmp(String S, String W) {
        if(W.length() == 0) return 0;
        //calculate partial table
        int count = 0;
        Set<Character> map = new HashSet<>();
        int[] partialTable = new int[W.length()];
        partialTable[0] = 0;
        map.add(W.charAt(0));
        for(int k = 1; k < W.length(); k ++) {
            map.add(W.charAt(k));
            if(W.charAt(k) == W.charAt(count)) {
                partialTable[k] = (++count);
            }else {
                if(count != 0 && W.charAt(k) == W.charAt(k - 1) && partialTable[k - 1] == partialTable[count -1] + 1) {//deal with special case (last 'a' in 'aabaaa')
                    partialTable[k] = count;
                }else {
                    count = 0;
                    if(W.charAt(k) == W.charAt(count)) partialTable[k] = (++count);
                    else partialTable[k] = count;
                }
            }
        }
        // start to find if W exist in S
        int i = 0, j = 0;
        while (i <= S.length() - W.length()) {
            for(; j < W.length(); j ++) {
                if(S.charAt(i + j) == W.charAt(j)) {
                    if(j == W.length() - 1) return i;
                }else {
                    if(!map.contains(S.charAt(i + j))) {
                        i += (j+1);
                        j = 0;
                        break;
                    }
                    if(j == 0) {
                        i ++;
                        j = 0;
                        break;
                    }
                    i += (j - partialTable[j - 1]); //jump to the proper position
                    j = partialTable[j - 1]; //jump the one already compared
                    break;
                }
            }
        }
        return -1;
    }

4. BM Alg.

BM algorithm was created by Boyer-Moore and J Strother Moore. Which is more efficient that KMP in most cases, especially in real world cases. That's why BM is widely used in content matching in files in real world.

Back to the example:S = "THIS IS A SIMPLE EXAMPLE" W = "EXAMPLE"

Solution:

round 1:

THIS IS A SIMPLE EXAMPLE
EXAMPLE

start matching from the end of EXAMPLE, E not match, and S not in EXAMPLE, so direct jump to the position after S:
round 2:

THIS IS A SIMPLE EXAMPLE
       EXAMPLE

E not match P, P is treated as a "bad character" and P's last position in EXAMPLE is 4 (count from 0), so should move pst(mapped by 'P' in 'EXAMPLE') - pst(last 'P' in 'EXAMPLE') = 6 - 4 = 2 steps forward.
round 3:

THIS IS A SIMPLE EXAMPLE
         EXAMPLE

As we can see, MPLE match (treat as "good character"), A and I not match ("bad character").
good character rule: pst(from 0, good character's position) - pst(last position of good character) = 3 - (-1) = 4
bad character rule: pst(bad character's positon) - pst(last position of bad character) = 2-(-1) = 3
4 > 3, so move 4 steps forward.
round 4:

THIS IS A SIMPLE EXAMPLE
             EXAMPLE

E not match A, A is bad character, its current mapping position is 6, A's last position in EXAMPLE is 2, so should move 6 - 2 = 4 steps forward.
round 5:

THIS IS A SIMPLE EXAMPLE
                 EXAMPLE

match, return start position in S: 17.

Show me the code!

    public static int bm(String S, String W) {
        if(W.length() == 0) return 0;
        Map<Character, List<Integer>> map = new HashMap<>();// to record each char's position
        for(int i = 0; i < W.length(); i ++) {
            if(map.get(W.charAt(i)) == null) 
                map.put(W.charAt(i), new ArrayList<>());
            map.get(W.charAt(i)).add(i);
        }
        int stepNum = 0;
        for(int k = 0; k <= S.length() - W.length(); k += stepNum) {
            for(int m = W.length() - 1; m >= 0; m --) {
                if(S.charAt(k + m) == W.charAt(m)) {//good char
                    if(m == 0) return k;//match found
                }else {//bad char
                    // steps calculate based on bad char 
                    int badStepNum = 0;
                    List<Integer> list = map.get(S.charAt(k + m));
                    if(list == null) {//not exist in W
                        badStepNum = m - (-1);
                    }else {
                        int badCharLastPst = -1;
                        for(int i = list.size() - 1; i >= 0; i --)
                            if(m > list.get(i) && m - list.get(i) < m - badCharLastPst)
                                badCharLastPst = list.get(i);
                        badStepNum = m - badCharLastPst;
                    }
                    // steps calculate based on good char 
                    int goodStepNum = 0;
                    if(m < W.length() - 1) {
                        list = map.get(S.charAt(k + m + 1));
                        if(list == null) {//not exist in W
                            goodStepNum = (m + 1) - (-1);
                        }else {
                            int goodCharLastPst = -1;
                            for(int i = list.size() - 1; i >= 0; i --)
                                if(m + 1 > list.get(i) && m + 1 - list.get(i) < m + 1 - goodCharLastPst)
                                    goodCharLastPst = list.get(i);
                            goodStepNum = m + 1 - goodCharLastPst;
                        }
                    }
                    stepNum = Math.max(badStepNum, goodStepNum);
                    break;
                }
            }
        }
        return -1;
    }

Reference

https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm
https://en.wikipedia.org/wiki/Boyer–Moore_string-search_algorithm

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末悔详,一起剝皮案震驚了整個(gè)濱河市次氨,隨后出現(xiàn)的幾起案子管嬉,更是在濱河造成了極大的恐慌,老刑警劉巖忿等,帶你破解...
    沈念sama閱讀 212,454評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡将饺,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門痛黎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來予弧,“玉大人,你說我怎么就攤上這事湖饱∫锤颍” “怎么了?”我有些...
    開封第一講書人閱讀 157,921評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵琉历,是天一觀的道長(zhǎng)坠七。 經(jīng)常有香客問我,道長(zhǎng)旗笔,這世上最難降的妖魔是什么彪置? 我笑而不...
    開封第一講書人閱讀 56,648評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮蝇恶,結(jié)果婚禮上拳魁,老公的妹妹穿的比我還像新娘。我一直安慰自己撮弧,他們只是感情好潘懊,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贿衍,像睡著了一般授舟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上贸辈,一...
    開封第一講書人閱讀 49,950評(píng)論 1 291
  • 那天释树,我揣著相機(jī)與錄音,去河邊找鬼擎淤。 笑死奢啥,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嘴拢。 我是一名探鬼主播桩盲,決...
    沈念sama閱讀 39,090評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼席吴!你這毒婦竟也來了赌结?” 一聲冷哼從身側(cè)響起捞蛋,我...
    開封第一講書人閱讀 37,817評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎姑曙,沒想到半個(gè)月后襟交,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,275評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伤靠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評(píng)論 2 327
  • 正文 我和宋清朗相戀三年捣域,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宴合。...
    茶點(diǎn)故事閱讀 38,724評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡焕梅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出卦洽,到底是詐尸還是另有隱情贞言,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評(píng)論 4 333
  • 正文 年R本政府宣布阀蒂,位于F島的核電站该窗,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚤霞。R本人自食惡果不足惜酗失,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評(píng)論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望昧绣。 院中可真熱鬧规肴,春花似錦、人聲如沸夜畴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贪绘。三九已至兑牡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間税灌,已是汗流浹背均函。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留垄琐,地道東北人边酒。 一個(gè)月前我還...
    沈念sama閱讀 46,503評(píng)論 2 361
  • 正文 我出身青樓靠粪,卻偏偏與公主長(zhǎng)得像据某,于是被迫代替她去往敵國(guó)和親饿肺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容