Questions¶
Difficulty: Medium
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.
Coding¶
python¶
# -*- coding: utf-8 -*-
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dict, ans, p1, p2 = {}, 0, 0, 0
while p2 < len(s):
p = dict.get(s[p2], None)
if p == None:
dict[s[p2]] = p2
p2 += 1
ans = max(ans, p2 - p1)
else:
while p1 <= p:
dict.pop(s[p1])
p1 += 1
p1 = p + 1
return ans