Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
For this question, I got two possible solutions. First, I use a Queue to maintain a sliding window, which contains only the non-duplicated string. For example, when a new element came in, I will first check whether this element already pushed in the queue. While True, I will pop the head element until there aren't any duplicated string. And I will maintain a variable to keep tracking the maximal length. That will be the final result.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)<2:
return len(s)
queue=[]
i=0
maximal=0
while i<len(s):
while s[i] in queue:
queue.pop(0)
queue.append(s[i])
maximal=max(maximal,len(queue))
i+=1
return maximal
The second solution is using a map, which records the index of every element we want to use. And if the incoming element is already used, we restart from the accordingly index.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)<2:
return len(s)
dp=""
i=0
maximal=0
dic={}
while i<len(s):
if s[i] not in dic:
dic[s[i]]=i
dp+=s[i]
maximal=max(maximal,len(dp))
i+=1
else:
i=dic[s[i]]+1
dic={}
dp=""
return maximal
The best solution is using maps for recording index of every element, and maintain a sliding window, start at start and end at i, where in the range(start, i), there are no duplicate element。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dic={}
start=0
res=0
for i,item in enumerate(s):
if item not in dic:
dic[item]=i
else:
res=max(res,i-start)
start=max(start,dic[item]+1)
dic[item]=i
return max(res,len(s)-start)
本文探讨了如何找出给定字符串中最长的无重复字符子串长度,提供了三种不同的算法解决方案,包括使用队列和映射的方法来维护滑动窗口内的非重复字符。
724

被折叠的 条评论
为什么被折叠?



