LeetCode题目链接

题意:给定一个字符串,求字母不重复的最长子序列。

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.

用队列模拟即可。如果下一个字母在已知序列中存在,那么重头删除直到删除到此元素。如果不存在于已知序列,则直接加入队列。这样每次更新都是一个合法的子序列,求出最大值即可。

class Solution:
    def lengthOfLongestSubstring(self, s):
        v, best = [], 0
        for i in s:
            if i in v:
                while i in v:
                    v.pop(0)
                v.append(i)
            else: v.append(i)
            best = max(best, len(v))
        return best

欢迎留言