KMP算法

KMP算法

str1 str2 求str2在str1中的開始位置
幾個(gè)概念:
1.最長前綴和最長后綴的匹配長度
2.依據(jù)概念1暑始,求出str2中每個(gè)元素的最長前綴和最長后綴匹配長度,得出數(shù)組next
3.利用next,開始對暴力算法進(jìn)行加速婴削,從而得到KMP算法廊镜。

下面講next數(shù)組怎么得到。
1.向前找唉俗。

package basic_class_02;

public class Code_01_KMP {

    public static int getIndexOf(String s, String m) {
        if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
            return -1;
        }
        char[] ss = s.toCharArray();
        char[] ms = m.toCharArray();
        int si = 0;
        int mi = 0;
        int[] next = getNextArray(ms);
        while (si < ss.length && mi < ms.length) {
            if (ss[si] == ms[mi]) {
                si++;
                mi++;
            } else if (next[mi] == -1) {
                si++;
            } else {
                mi = next[mi];
            }
        }
        return mi == ms.length ? si - mi : -1;
    }

    public static int[] getNextArray(char[] ms) {
        if (ms.length == 1) {
            return new int[] { -1 };
        }
        int[] next = new int[ms.length];
        next[0] = -1;
        next[1] = 0;
        int pos = 2;
        int cn = 0;
        while (pos < next.length) {
            if (ms[pos - 1] == ms[cn]) {
                next[pos++] = ++cn;
            } else if (cn > 0) {
                cn = next[cn];
            } else {
                next[pos++] = 0;
            }
        }
        return next;
    }

    public static void main(String[] args) {
        String str = "abcabcababaccc";
        String match = "ababa";
        System.out.println(getIndexOf(str, match));

    }

}

KMP算法擴(kuò)展題目指一:

題目
給定一個(gè)字符串str1嗤朴, 只能往str1的后面添加字符變成str2。
要求1: str2必須包含兩個(gè)str1虫溜, 兩個(gè)str1可以有重合雹姊, 但是不
能以同一個(gè)位置開頭。
要求2: str2盡量短
最終返回str2
舉例:
str1 = 123吼渡, str2 = 123123 時(shí)容为, 包含兩個(gè)str1, 且不以相同
位置開頭寺酪, 且str2最短坎背。
str1 = 123123, str2 = 123123123 時(shí)寄雀, 包含兩個(gè)str1得滤, 且不
以相同位置開頭, 且str2最短盒犹。
str1 = 111懂更, str2 = 1111 時(shí), 包含兩個(gè)str1急膀, 且不以相同位
置開頭沮协, 且str2最短。

package basic_class_02;

public class Code_02_KMP_ShortestHaveTwice {

    public static String answer(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        char[] chas = str.toCharArray();
        if (chas.length == 1) {
            return str + str;
        }
        if (chas.length == 2) {
            return chas[0] == chas[1] ? (str + String.valueOf(chas[0])) : (str + str);
        }
        int endNext = endNextLength(chas);
        return str + str.substring(endNext);
    }

    public static int endNextLength(char[] chas) {
        int[] next = new int[chas.length + 1];
        next[0] = -1;
        next[1] = 0;
        int pos = 2;
        int cn = 0;
        while (pos < next.length) {
            if (chas[pos - 1] == chas[cn]) {
                next[pos++] = ++cn;
            } else if (cn > 0) {
                cn = next[cn];
            } else {
                next[pos++] = 0;
            }
        }
        return next[next.length - 1];
    }

    public static void main(String[] args) {
        String test1 = "a";
        System.out.println(answer(test1));

        String test2 = "aa";
        System.out.println(answer(test2));

        String test3 = "ab";
        System.out.println(answer(test3));

        String test4 = "abcdabcd";
        System.out.println(answer(test4));

        String test5 = "abracadabra";
        System.out.println(answer(test5));

    }

}

給定兩個(gè)二叉樹T1和T2卓嫂, 返回T1的某個(gè)子樹結(jié)構(gòu)是否與T2的結(jié)構(gòu)相等

package basic_class_02;

public class Code_03_KMP_T1SubtreeEqualsT2 {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isSubtree(Node t1, Node t2) {
        String t1Str = serialByPre(t1);
        String t2Str = serialByPre(t2);
        return getIndexOf(t1Str, t2Str) != -1;
    }

    public static String serialByPre(Node head) {
        if (head == null) {
            return "#!";
        }
        String res = head.value + "!";
        res += serialByPre(head.left);
        res += serialByPre(head.right);
        return res;
    }

    // KMP
    public static int getIndexOf(String s, String m) {
        if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
            return -1;
        }
        char[] ss = s.toCharArray();
        char[] ms = m.toCharArray();
        int[] nextArr = getNextArray(ms);
        int index = 0;
        int mi = 0;
        while (index < ss.length && mi < ms.length) {
            if (ss[index] == ms[mi]) {
                index++;
                mi++;
            } else if (nextArr[mi] == -1) {
                index++;
            } else {
                mi = nextArr[mi];
            }
        }
        return mi == ms.length ? index - mi : -1;
    }

    public static int[] getNextArray(char[] ms) {
        if (ms.length == 1) {
            return new int[] { -1 };
        }
        int[] nextArr = new int[ms.length];
        nextArr[0] = -1;
        nextArr[1] = 0;
        int pos = 2;
        int cn = 0;
        while (pos < nextArr.length) {
            if (ms[pos - 1] == ms[cn]) {
                nextArr[pos++] = ++cn;
            } else if (cn > 0) {
                cn = nextArr[cn];
            } else {
                nextArr[pos++] = 0;
            }
        }
        return nextArr;
    }

    public static void main(String[] args) {
        Node t1 = new Node(1);
        t1.left = new Node(2);
        t1.right = new Node(3);
        t1.left.left = new Node(4);
        t1.left.right = new Node(5);
        t1.right.left = new Node(6);
        t1.right.right = new Node(7);
        t1.left.left.right = new Node(8);
        t1.left.right.left = new Node(9);

        Node t2 = new Node(2);
        t2.left = new Node(4);
        t2.left.right = new Node(8);
        t2.right = new Node(5);
        t2.right.left = new Node(9);

        System.out.println(isSubtree(t1, t2));

    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末慷暂,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子晨雳,更是在濱河造成了極大的恐慌行瑞,老刑警劉巖奸腺,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異血久,居然都是意外死亡突照,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門氧吐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來讹蘑,“玉大人,你說我怎么就攤上這事副砍∠沃” “怎么了庄岖?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵豁翎,是天一觀的道長。 經(jīng)常有香客問我隅忿,道長心剥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任背桐,我火速辦了婚禮优烧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘链峭。我一直安慰自己畦娄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布弊仪。 她就那樣靜靜地躺著熙卡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪励饵。 梳的紋絲不亂的頭發(fā)上驳癌,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機(jī)與錄音役听,去河邊找鬼颓鲜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛典予,可吹牛的內(nèi)容都是我干的甜滨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼瘤袖,長吁一口氣:“原來是場噩夢啊……” “哼衣摩!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起孽椰,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤昭娩,失蹤者是張志新(化名)和其女友劉穎凛篙,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體栏渺,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡呛梆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了磕诊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片填物。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖霎终,靈堂內(nèi)的尸體忽然破棺而出滞磺,到底是詐尸還是另有隱情,我是刑警寧澤莱褒,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布击困,位于F島的核電站,受9級特大地震影響广凸,放射性物質(zhì)發(fā)生泄漏阅茶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一谅海、第九天 我趴在偏房一處隱蔽的房頂上張望脸哀。 院中可真熱鬧,春花似錦扭吁、人聲如沸撞蜂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蝌诡。三九已至,卻和暖如春系馆,著一層夾襖步出監(jiān)牢的瞬間送漠,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工由蘑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留闽寡,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓尼酿,卻偏偏與公主長得像爷狈,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子裳擎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354

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