Simple string matching-Introduction to Algorithms

Source: Internet
Author: User

The collation string T = abcabaabaadac, the string P = abaa, determines whether P is a substring of T, which is a string matching problem. T is called Text and P is called Pattern ). the string matching process with simple algorithm ideas can be seen as a "template" P of the Inclusion pattern moving along text T, at the same time, pay attention to whether the characters in the template are equal to the corresponding characters in the text for each shift. The maximum number of Outer Loops is len (s)-len (p), and the maximum number of inner loops is len (p ). worst case time complexity: O (len (T)-len (P) + 1) * len (P) Two for loops, the code is relatively simple, but the efficiency is very low. algorithm code [cpp] # include <stdio. h> # include <stdlib. h> # include <string. h> void main () {char part [20], str [50]; int I, flag, j, len_p, len_s, k; while (scanf ("% s", part, str )! = EOF) {// obtain the string length len_p = strlen (part); len_s = strlen (str); // simple string matching algorithm for (I = 0, flag = 0; I <len_s-len_p + 1; I ++) {for (j = I, k = 0; part [k] = str [j] & part [k]! = '\ 0' & str [k]! = '\ 0'; j ++, k ++) {} if (k> 0 & part [k] =' \ 0') {flag = 1; break;} http: // output matching successful or failed if (flag) printf ("matching successful, matching location: % d \ n", I + 1 ); else printf ("matching failed! \ N ");}} in algorithm notation and terminology, Σ * represents the length of x, a collection string of all finite-length strings in the Σ alphabet. | x | represents the link between x and y as xy, the length is | x | + | y | x = yw, y is the prefix of x, and w is the suffix of x.

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.