From c++strstr to string matching algorithm

Source: Internet
Author: User

String matching defines two nouns: a pattern string and a text string. Our task is to find the first occurrence of the pattern string in the text string, if we find the subscript to return the position, if no return-1 is found. This is actually a function of the C + + language:

extern Char *strstr (char *str1, const char *STR2);

For the explanation of this function:

STR1: Target str2: To find the object return value: If STR2 is a substring of str1, it returns the first occurrence of str2 at STR1, or null if STR2 is not a substring of str1. For example: Char str[]= "1234xyz"; char *str1=strstr (str, "cout"); str1 << Endl; display: 34xyz

The return value is a pointer to the position of the first occurrence of the pattern string in the text string.

Brute force algorithm for string lookup

First look at a topic on leetcode, implement this function int strStr (string haystack, string needle); Requires the return of the subscript value of the pattern string in the text string.

1. If the pattern string is NULL, return 0.2 directly. If the pattern string is longer than the text string, it must not be found, and returns-1.3. If present, the scope of the lookup can be limited to the 0~s.size ()-p.size () of the text string;

So the code implementation of the Brute force algorithm:

int StrStr (String haystack, string needle) {int i = 0;//pattern string is empty if (Needle.empty ()) {return 0;} The size of the text string is less than the pattern string if (Haystack.size () < Needle.size ()) {return-1;} Determine the range of lookups for (i = 0; I <= haystack.size ()-needle.size (); ++i) {int J = 0;for (j = 0; J < needle.size (); ++j) {if (Haystac K[I+J]! = Needle[j]) {break;}} Forif (j = = Needle.size ()) {return i;}} Forif (i = = Haystack.size ()-needle.size () + 1) {return-1;}}

  

From c++strstr to 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.