本文实例讲述了python查找最长不包含重复字符的子字符串算法。分享给大家供大家参考,具体如下:
题目描述
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。例如在“arabcacfr”中,最长的不包含重复字符的子字符串是“acfr”,长度为4
采用字典的方法,最后输出所有最长字符的列表
算法示例:
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
|
# -*- coding:utf-8 -*- #! python3 class solution: def __init__( self ): self .maxstring = [] def longestsubstring( self , inputstring): if inputstring = = '': return '' dic = {} dic = dic.fromkeys(inputstring, 0 ) self .maxstring.append(inputstring[ 0 ]) for i in range ( len (inputstring)): for j in range (i, len (inputstring)): if dic[inputstring[j]] ! = 0 : dic = dic.fromkeys(inputstring, 0 ) break else : if j - i + 1 > len ( self .maxstring[ 0 ]): self .maxstring = [] self .maxstring.append(inputstring[i:j + 1 ]) elif j - i + 1 = = len ( self .maxstring[ 0 ]): self .maxstring.append(inputstring[i:j + 1 ]) dic[inputstring[j]] + = 1 inputstring = 'arabcacfr' sol = solution() sol.longestsubstring(inputstring) print (sol.maxstring) #输出:['rabc', 'acfr'] |
运行结果:
希望本文所述对大家python程序设计有所帮助。
原文链接:https://blog.csdn.net/weixin_36372879/article/details/84861449