Leetcode Longest Substring Without Repeating Characters

题目:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


问题描述:在字符串中寻找最长无重复的子串,返回其最大长度

解题方法描述:

转载:http://blog.csdn.net/likecool21/article/details/10858799

    因为字符的Ascii码值是唯一的,因此可以建立一个数组,数组的下标表示这个字符的ASCII码,范围为0-255,则可设置数组大小为256,数组中元素表示其在字符串中的位置。寻找的过程为:逐个便利字符,将字符的位置存入其对应的ASCII下标下,当遇到和之前重复的字符(前一次出现称为Occur 1, 这一次出现称为Occur 2)时,即遇到了一个可能的最大值;进行比较后,将下一次扫描的起点设置为刚才这个重复字符的Occur 1的后一位即可。表示如图:




Python 代码如下:

用列表实现数组,初始化为-1.

由c++程序翻译的,估计有更简单的Python写法,有待继续改进。

Leetcode 的Python 环境中不支持中文注释。

真正编程时如果想用中文字符,在文件开始出加入:# -*- coding: cp936 -*-


class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        l=len(s)
        if l<=1:
            return l
        dic=[-1,]*256            #数组初始化
        start=0
        res=0
        i=0
        for i in range(0,l):
          
            if dic[ord(s[i])]!=-1:                    #元素已经存在 则可能有最大长度
                res=max(res,i-start) 
                for j in range(start,dic[ord(s[i])]):     #将重复部分清空
                    dic[ord(s[j])]=-1
                if dic[ord(s[i])]+1>start:               #开始位置设为重复位置的下一位
                    start=dic[ord(s[i])]+1
                dic[ord(s[i])]=i
            else:
                dic[ord(s[i])]=i
        res=max(res,l-start)            
        return res















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值