本文摘自php中文网,作者不言,侵删。
这篇文章主要介绍了Python实现针对给定字符串寻找最长非重复子串的方法,涉及Python针对字符串的遍历、排序、计算等相关操作技巧,需要的朋友可以参考下本文实例讲述了Python实现针对给定字符串寻找最长非重复子串的方法。分享给大家供大家参考,具体如下:
问题:
给定一个字符串,寻找其中最长的重复子序列,如果字符串是单个字符组成的话如“aaaaaaaaaaaaa”那么满足要求的输出就是a
思路:
这里的思路有两种是我能想到的
(1)从头开始遍历字符串,设置标志位,在往后走的过程中当发现和之前标志位重合的时候就回头检查一下这个新出现的子串是否跟前面字符串或者前面字符串的子串相同,相同则记录该子串并计数加1,直至处理完毕
(2)利用滑窗切片的机制,生成所有的切片接下来统计和处理,主要利用到了两次排序的功能
本文采用的是第二种方法,下面是具体实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | from collections import Counter
def slice_window(one_str,w = 1 ):
res_list = []
for i in range ( 0 , len (one_str) - w + 1 ):
res_list.append(one_str[i:i + w])
return res_list
def main_func(one_str):
all_sub = []
for i in range ( 1 , len (one_str)):
all_sub + = slice_window(one_str,i)
res_dict = {}
threshold = Counter(all_sub).most_common( 1 )[ 0 ][ 1 ]
slice_w = Counter(all_sub).most_common( 1 )[ 0 ][ 0 ]
for one in all_sub:
if one in res_dict:
res_dict[one] + = 1
else :
res_dict[one] = 1
sorted_list = sorted (res_dict.items(), key = lambda e:e[ 1 ], reverse = True )
tmp_list = [one for one in sorted_list if one[ 1 ]> = threshold]
tmp_list.sort( lambda x,y: cmp ( len (x[ 0 ]), len (y[ 0 ])),reverse = True )
print tmp_list[ 0 ][ 0 ]
if __name__ = = '__main__' :
print "脚本之家测试结果:"
one_str = 'abcabcd'
two_str = 'abcabcabd'
three_str = 'bbbbbbb'
main_func(one_str)
main_func(two_str)
main_func(three_str)
|
结果如下:

相关推荐:
Python实现按照指定要求逆序输出一个数字
python实现在IDLE中输入多行的方法
以上就是Python实现针对给定字符串寻找最长非重复子串的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python以什么划分语句块
Python64位和32位区别
Python中t是什么意思
Python matplotlib中文显示参数设置解析_Python
Python可以用来干什么?
Python中基本的数据结构--列表
Python dict怎么实现的
怎样操作Python遍历numpy数组
Python中int是什么意思
Python如何发送?Python发送email的三种方式介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python实现针对给定字符串寻找最长非重复子串