LeetCode 3. Longest Substring Without Repeating Characters---Python实现

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

题意很明白,在一个字符串中找一个最长的不重复连续字串,选用一个字典来存储每个字符的位置,进行遍历即可。具体代码分析如下。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        usechar={}
        start=length=0 # /length=i=0
        for i in range(len(s)):  # for i in len(s):
            if s[i] in usechar and start <=usechar[s[i]]:  # if s[i] in usechar and start<=s[i]:
                start=usechar[s[i]]+1# start=s[i]+1 #直接从重复的之后再来算啊。usechar里面的都是唯一的啊。
            else:
                length=max(length,i-start+1)
            usechar[s[i]]=i;
        return length

点赞