基于python 3.5 所做的找出来一个字符串中最长不重复子串算法

功能:找出来一个字符串中最长不重复子串

 1 def find_longest_no_repeat_substr(one_str):
 2     #定义一个列表用于存储非重复字符子串
 3     res_list=[]
 4     #获得字符串长度
 5     length=len(one_str)
 6     for i in range(length):
 7         tmp=one_str[i]
 8         for j in range(i+1, length):
 9             #用取到的字符与tmp中的字符相匹配,匹配不成功tmp字符继续增加,匹配成功直接跳出循环加入到res_list列表中
10             if one_str[j] not in tmp:
11                 tmp+=one_str[j]
12             else:
13                 #break只能跳出一层循环,并对if-else判断语句无效果,只对循环起作用
14                 break
15         res_list.append(tmp)
16     #拿到列表总长度
17     n = len(res_list)
18     # 外层循环确定比较的轮数,x是下标
19     for x in range(n - 1):
20         # 内层循环开始比较,y是下标
21         for y in range(x + 1, n):
22             if len(res_list[x]) > len(res_list[y]):
23                 # 让res_list[x]和res_list[y]列表中每一个元素比较,进行字符长度从小到大排序
24                 res_list[x], res_list[y] = res_list[y], res_list[x]
25     return res_list[-1]
26 
27 
28 if __name__ == '__main__':
29     one_str_list=['120135435','abdfkjkgdok','123456780423349']
30     for one_str in one_str_list:
31         res=find_longest_no_repeat_substr(one_str)
32         print('{0}最长非重复子串为:{1}'.format(one_str, res))

这里用到了排序算法

 1 #拿到列表总长度
 2     n = len(res_list)
 3     # 外层循环确定比较的轮数,x是下标
 4     for x in range(n - 1):
 5         # 内层循环开始比较,y是下标
 6         for y in range(x + 1, n):
 7             if len(res_list[x]) > len(res_list[y]):
 8                 # 让res_list[x]和res_list[y]列表中每一个元素比较,进行字符长度从小到大排序
 9                 res_list[x], res_list[y] = res_list[y], res_list[x]
10     return res_list[-1]

最后是输出值

1     # 120135435最长非重复子串为:201354
2     # abdfkjkgdok最长非重复子串为:abdfkj
3     # 123456780423349最长非重复子串为:123456780

猜你喜欢

转载自www.cnblogs.com/weijiazheng/p/10486545.html
今日推荐