String matching algorithm KMP Java implementation

Source: Internet
Author: User
Tags comparison table

See some of the KMP realization, according to gourd painting scoop, very rigid, prefix what is completely unnecessary.

KMP The core idea of the algorithm: first to the search string generation offset comparison table, matching from left to right in order to compare (bm from right to left, claiming to be faster than KMP), equal to the document and search string subscript +1 iteration, otherwise check the table, positioning the optimal offset position (document subscript unchanged, search string subscript change). The exception is, if the character does not match, if the search string subscript is 0, then the document subscript +1, continue the iteration comparison.

Import Java.util.arrays;public class Kmpsearch {public static int[] table;public static void Generatetab (String key) {//query The string generates an offset table, an iteration can be int len=key.length (); table=new Int[len]; Arrays.fill (table, 0), for (int i=1;i<len;i++) {if (Key.charat (i) ==key.charat (Table[i-1])) {table[i]=table[i-1]+1;}} for (int v:table) {System.out.print (v);} System.out.println ();} public static int Kmpsearchs (String doc,string key) {Generatetab (key); int Result=-1;int doc_size=doc.length (), key_size =key.length (), Doc_iter=0,key_iter=0;while (doc_iter<doc_size) {//traverse the document being queried, again, a single-layer loop can implement →_→ if (Doc.charat (doc_ ITER) ==key.charat (Key_iter)) {doc_iter++;key_iter++;} Else{if (key_iter==0) {doc_iter++;continue;} Else{key_iter=table[key_iter-1];continue;}} if (key_iter==key_size) {result=doc_iter-key_size;break;}} return result;} public static void Main (string[] args) {int I=kmpsearchs ("BBC Abcdab Abcdabcdabde", "abcdabd"); System.out.println (i);}}


Algorithm explanation Reference HTTP://ITINDEX.NET/DETAIL/45421-%E5%AD%97%E7%AC%A6%E4%B8%B2-%E5%8C%B9%E9%85%8D-KMP

String matching algorithm KMP Java implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.