One of the string pattern matching algorithms: Naïve pattern matching algorithm

Source: Internet
Author: User


The string being searched is called the main string, and the strings to be searched are called pattern strings. The basic idea of naive pattern matching algorithm:

Starts each character of the main string as a substring and matches the pattern string. Cycle through the main string, and each character starts with a small loop of the length of the pattern string until the match succeeds or all traversal is complete.

The code implementation is simple:

    intSTRSTR (Char*haystack,Char*needle) { for(inti =0; ; ++i) { for(intj =0; ; ++J) {if(!needle[j])returnIif(!haystack[i + j])return-1;if(Needle[j]! = Haystack[i + j]) Break; }        }    }

The time complexity analysis of the naïve pattern matching algorithm is as follows:

Case

Complexity of Time

Note

Best case

O (1)

The match was successful at first.

Worst case scenario

O ((n-m+1) *m)

Each unsuccessful match occurs at the last character of the pattern string.

Average situation

O (N+M)

According to the equal probability principle, the average is (n+m)/2-time lookup.

Note: where n is the main string length, M is the pattern string length.

One of the string pattern matching algorithms: Naïve pattern 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.