Longest Substring without Repeating Characters

题目详情:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

自己写的代码,主要思路就是:存储字符串中每个元素的位置;如果当前字符c在前边出现过,设为start,那么取的该位置,并更新c的位置,设为nowPos。这里有个变量m,m存储”历史上”start的最大值,程序需要根据m的值来确定start的值,如果m的值较大,那么字符串s中从start到nowPos之间必定有重复元素,所以需要将m的值赋给start,以保证[start,nowPos]之间没有重复元素。

#-*- coding:utf-8 -*-
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        i,j,length=0,0,len(s)
        maxLength,pos,d=0,{},{}
        start,m=0,-1
        while iif pos.get(s[i])==None:#如果s[i]没有出现过
                pos[s[i]]=i #添加到d中
            else:#s[i]已经在d中了
                start=pos[s[i]]+1#获得上一次出现s[i]的位置
                pos[s[i]]=i#更新s[i]出现的位置
                if start#m存储无重复元素的可能子串的最大下标,如果start
                    start=m#那么s[start:i+1]肯定有重复元素
                elif start>m:#如果start>m
                    m=start  #更新s
            dis=i-start+1#求出这次无重复元素子串的长度,start为子串的开始位置
            if dis>maxLength:#如果dis较大
                maxLength=dis#那么更新最大长度的值
            i=i+1
        return maxLength

你可能感兴趣的:(leetCode)