Introduction to Algorithm--naïve string matching algorithm

Source: Internet
Author: User

Package Org.loda.string;import org.junit.assert;/** * * @ClassName: Naivestringmatcher * @Description: Plain String Lookup * * TEXT:ABCABAABCABAC * Pattern:abaa * * @author Minjun * @date July 7, 2015 afternoon 4:02:14 * */public Clas s naivestringmatcher {public static void main (string[] args) throws Exception {//original text String text = "Abcabaabcabac";//Lookup Mode string pattern = "Abaa";//The position of the first occurrence of the pattern in the text int index = indexOf (text, pattern); SYSTEM.OUT.PRINTLN (index);} private static int IndexOf (string text, string pattern) {assert.assertnotnull (text); Assert.assertnotnull (pattern); int tLen = Text.length (); int plen = Pattern.length (); if (TLen < Plen) return-1;// Offset each time to the right to compare text and patternfor (int i = 0; i < Tlen-plen + 1; i++) {int j;//up to Plen wheel comparison for (j = 0; J < Plen; J + +) {/ /If found unequal immediately stop comparing if (Text.charat (i + j)! = Pattern.charat (j)) {Break;}} After the comparison is complete, if you compare plen times, the description performs a complete comparison and finds the location of the pattern iif (j = = Plen) {return i;}} If the position of the pattern is still not found, the description does not exist in the text patternreturn-1;}}



Introduction to Algorithm--naïve string matching algorithm

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.