Python查找最长不包含重复字符的子字符串算法示例

yipeiwu_com7年前Python基础

本文实例讲述了Python查找最长不包含重复字符的子字符串算法。分享给大家供大家参考,具体如下:

题目描述

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。例如在“arabcacfr”中,最长的不包含重复字符的子字符串是“acfr”,长度为4

采用字典的方法,最后输出所有最长字符的列表

算法示例:

# -*- 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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

用python处理图片之打开\显示\保存图像的方法

用python处理图片之打开\显示\保存图像的方法

一提到数字图像处理,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1、不开源,价格贵 2、软件容量大。一般3G以上,高版本甚至达5G以上。 3、只能做研究,不易转化成...

Python中生成Epoch的方法

在Python2中datetime对象没有timestamp方法,不能很方便的生成epoch,现有方法没有处理很容易导致错误。关于Epoch可以参见时区与Epoch 0 Python中生...

python中的迭代和可迭代对象代码示例

什么是迭代(iteration)呢? 给定一个list或者tuple,通过for循环来遍历这个list或者tuple、这种遍历就是迭代(iteration)。只要是可迭代的对象都可以进行...

python 捕获shell脚本的输出结果实例

import subprocess output =Popen(["mycmd","myarg"], stdout=PIPE).communicate()[0] import subp...

pytorch方法测试详解——归一化(BatchNorm2d)

pytorch方法测试详解——归一化(BatchNorm2d)

测试代码: import torch import torch.nn as nn m = nn.BatchNorm2d(2,affine=True) #权重w和偏重将被使用 in...