python找最长的字符串_Python实现针对给定字符串寻找最长非重复子串的方法

#!usr/bin/env python

#encoding:utf-8

'''''

__Author__:沂水寒城

功能:给定一个字符串,寻找最长重复子串

'''

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={}

#print Counter(all_sub)

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

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值