Skip to content

Commit abc6fb2

Browse files
author
shengshijun
committed
update README
kmp算法
1 parent 0cd9ba1 commit abc6fb2

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ algorithm
4545
##字符串匹配算法
4646
1. 朴素算法
4747
2. Rabin-Karp算法
48-
3. 有限自动机字符串匹配
49-
4. KMP算法
48+
3. KMP算法
5049

5150

5251
#数据结构

string/kmp.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+

0 commit comments

Comments
 (0)