Longest Substring Without Repeating Characters
Description:
Given a string, find the length of the longest substring without repeating characters.
Example
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.
Challenge
O(n) time
Code:
class Solution:
"""
@param s: a string
@return: an integer
"""
def lengthOfLongestSubstring(self, s):
# write your code here
if len(s)<2:
return len(s)
dic = {}
start = 0
res = 0
for i in range(len(s)):
if s[i] in dic:
res = max(res, len(dic))
while s[i] in dic:
dic.pop(s[start])
start += 1
dic[s[i]]=1
res = max(res, len(dic))
return res