Data structure-String-Pattern match

来源:互联网 发布:淘宝上的药可以买吗 编辑:程序博客网 时间:2024/05/05 13:55

Pattern matching is a powerful and elegant way of extracitng information from some certain objectives.And it plays a central role in functional programming.

 

There are two kinds of pattern match.

Brute algorithm:

Time complexity:O(m*n)

KMP algorithm:

Time complexity:O(m+n)

 

j

1

2

3

4

5

6

7

8

9

10

pattern string

a

b

a

a

b

c

a

c

a

b

next[j]

0

1

1

2

2

3

1

2

Thinking process(two methods):

1) if j=1  -->  next[j]=0    

    if set is not empty  -->  next[j]=Max{k|1<k<j,且'p1…pk'='p(j-k+1)…p(j-1)'}

    other situation  -->  1.

2) if j=x  -->  compare pattern string of next[x-1]  and pattern string of

     next[next[x-1]]  --> 

       if the value is same,next[x]=next[x-1]+1;

       else,we should continue to compare the pattern string of (j=next[next[x-1]]) and pattern string of (j=x-1).

Pay attention: while j=1,the corresponding pattern string still differs from the pattern string of next[next[x-1]]  --> next[x]=0+1=1.

 

 

0 0