java實現KMP演算法

來源:互聯網
上載者:User

標籤:java   kmp   

package net.yk.string;public class KMP {public static void main(String[] args) {String major = "abababcabcabcda";String mode = "abcd";int[] next = new KMP().next(mode);System.out.println(new KMP().index_KMP(major, mode, 1, next));}/** * 擷取字串的部分匹配值 * @param str * @return */int[] next(String str) {// 擷取模式串的長度int len = str.length();// 建立字元數組用來儲存模式串char[] mode = new char[len + 1];int[] next = new int[len + 1];// 將模式串拷貝到字元數組中,從下標1開始str.getChars(0, len, mode, 1);int i = 1, j = 0;next[1] = 0;while (i < len) {if (j == 0 || mode[i] == mode[j]) {i++;j++;next[i] = j;} elsej = next[j];}return next;}/** * KMP 演算法 *  * @param major * @param mode * @param pos * @param next * @return */int index_KMP(String major, String mode, int pos, int[] next) {int majorL = major.length();int modeL = mode.length();//從下標1開始儲存資料char majorChar[] = new char[majorL + 1];char modeChar[] = new char[modeL + 1];major.getChars(0, majorL, majorChar, 1);mode.getChars(0, modeL, modeChar, 1);int i = pos, j = 1;while (i <= majorL && j <= modeL) {if (j == 0 || majorChar[i] == modeChar[j]) {++i;++j;} elsej = next[j];}if (j > modeL) {return i - modeL;} elsereturn 0;}}


java實現KMP演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.