005_013 Python 寻找子序列 字符串应该用find 否则用KMP
2014-04-06 00:30
519 查看
代码如下:
打印结果如下:
中国
1
4
#encoding=utf-8 print '中国' #寻找子序列 #字符串应该用find 否则用KMP def KnuthMorrisPratt(text, pattern): pattern = list(pattern) length = len(pattern) shifts = [1] * (length + 1) shift = 1 for pos, pat in enumerate(pattern): while shift <= pos and pat != pattern[pos-shift]: shift += shifts[pos-shift] shifts[pos+1] = shift startPos = 0 matchLen = 0 for c in text: while matchLen == length or matchLen >= 0 and pattern[matchLen] != c: startPos += shifts[matchLen] matchLen -= shifts[matchLen] matchLen += 1 if matchLen == length: yield startPos for i in KnuthMorrisPratt([1,2,3,4,2,3],[2,3]): print i
打印结果如下:
中国
1
4
相关文章推荐
- 005_005 Python 根据字符串中的数字排序,如f10应该在f2后面
- python序列类型字符串的方法L.index()与L.find()区别
- 005_008 Python 获取序列中最小的几个元素
- python字符串字串查找 find和index方法
- Python: 利用序列的分片操作逆序字符串
- 序列之一 字符串 (python)
- Python之字符串方法find( )
- 关于寻找两个字符串中最长子序列的问题
- Python数据类型——序列(列表、元组、字符串)
- [Language]Python序列--字符串和列表和元组
- python序列:字符串,元组和列表
- Python中字符串、序列的遍历
- 九度笔记之 1342:寻找最长合法括号序列II(25分)-给括号当红娘,解决最长合法字符串问题
- Python核心编程--学习笔记--6--序列(上)字符串
- 005_009 Python 在排序已经完成的序列中查找元素
- python 序列:字符串、列表和元组
- KMP的妙用(利用next数组寻找字符串的循环节)
- Python学习笔记_元组、字符串、序列
- python字符串字串查找 find和index方法
- python核心编程学习记录之序列(字符串元组列表)