Programmer interview question selection (52): String Matching implementation (backtracking and non-backtracking algorithms)

Source: Internet
Author: User

Backtracking:

Const char * mystrstr (const char * Text, const char * pattern)
2 {
3 int I = 0, j = 0;
4
5 while (pattern [I] & text [J])
6 {
7 if (pattern [I] = text [J])
8 {
9 + + I;
10 + + J;
11}
12 else
13 {
14 I = 0;
15 J = J-I + 1;
16}
17} // while
18
19 if (! Pattern [I])
20 {
21 return text + J-I;
22}
23 else
24 {
25 return 0;
26}
27}

No backtracking:

# Include <cstring>
2 int BM (const char * Text, const char * pattern)
3 {
4 int arrshifttable [256];
5 Int tlen = strlen (text );
6 int Plen = strlen (pattern );
7 int currpos, treadpos, preadpos;
8
9 // exclude NUL
10 For (INT I = 1; I <sizeof arrshifttable/sizeof (INT); I ++)
11 {
12 arrshifttable [I] = Plen;
13}
14
15 // exclude the last char in Pattern
16 For (INT I = 0; I <Plen-1; I ++)
17 {
18 arrshifttable [pattern [I] = Plen-1-I;
19}
20
21 For (currpos = Plen-1; currpos <tlen;/** // * null */)
22 {
23 For (preadpos = Plen-1, treadpos = currpos;
24 preadpos> = 0 & pattern [preadpos] = text [treadpos];
25 preadpos --, treadpos --)
26/** // * null */;
27
28 If (preadpos <0)
29 {
30 return treadpos + 1;
31}
32 else
33 {
34 currpos + = arrshifttable [Text [currpos];
35}
36
37} // outer
38
39 return-1;
40}

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.