File tree Expand file tree Collapse file tree 2 files changed +42
-2
lines changed Expand file tree Collapse file tree 2 files changed +42
-2
lines changed Original file line number Diff line number Diff line change @@ -45,8 +45,7 @@ algorithm
45
45
##字符串匹配算法
46
46
1 . 朴素算法
47
47
2 . Rabin-Karp算法
48
- 3 . 有限自动机字符串匹配
49
- 4 . KMP算法
48
+ 3 . KMP算法
50
49
51
50
52
51
#数据结构
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python
2
+ # -*- coding:UTF-8
3
+ __author__ = 'shenshijun'
4
+
5
+
6
+ def match (origin , pattern ):
7
+ origin_len = len (origin )
8
+ pattern_len = len (pattern )
9
+
10
+ def build_next ():
11
+ _next_list = [0 for x in xrange (pattern_len )]
12
+ last_match = 0
13
+ for cur_index in xrange (1 , pattern_len ):
14
+ while last_match > 0 and pattern [last_match ] != pattern [cur_index ]:
15
+ last_match = _next_list [last_match ]
16
+ if pattern [last_match ] == pattern [cur_index ]:
17
+ last_match += 1
18
+ _next_list [cur_index ] = last_match
19
+ return _next_list
20
+
21
+ origin_index , pattern_index = 0 , 0
22
+ next_list = build_next ()
23
+ while origin_index < origin_len :
24
+ if pattern [pattern_index ] == origin [origin_index ]:
25
+ pattern_index += 1
26
+ origin_index += 1
27
+ while pattern_index > 0 and origin [origin_index ] != pattern [pattern_index ]:
28
+ pattern_index = next_list [pattern_index ]
29
+ if pattern_index == pattern_len :
30
+ return origin_index - pattern_len
31
+
32
+
33
+ def main ():
34
+ print match ("sb" , 'sb' )
35
+
36
+
37
+ if __name__ == "__main__" :
38
+ main ()
39
+
40
+
41
+
You can’t perform that action at this time.
0 commit comments