题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/
description
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
实现思路:
我们可以借助一个队列来实现。
逐个将字符放入队列中,如果发现当前字符在队列中已经存在,那么需将队列中的字符个数放入一个数组中,与此同时,将与当前字符相同的前面的那个字符之前的内容(包含它)全部移除队列(因为已经计算过了大小),同时将当前的这个字符放入队列。
python3 实现:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 1:
return 0
if len(s) == 1:
return 1
queue = [0]
num = []
queue[0] = s[0]
for c in s[1:]:
if c in queue:
num.append(len(queue))
temp = queue[0]
while temp != c:
queue.pop(0)
temp = queue[0]
else:
queue.pop(0)
queue.append(c)
else:
queue.append(c)
num.append(len(queue))
return max(num)
s = Solution()
rs = s.lengthOfLongestSubstring(input())
print(rs)