Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: Because the longest sub-string is repeated characters without "wke", so its length is 3.
Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.
1 Sliding Window
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s: return 0
d = {} #用来记录每个字符出现的下标,重复就替换
maxlength = 0
left_idx = 0#窗口起点
for i in range(len(s)):
if s[i] in d and left_idx <= d[s[i]]:#出现重复并且窗口起始点小于s[i]上一次出现的坐标就修改窗口的起点
left_idx = d[s[i]] + 1
maxlength = max(maxlength, i - left_idx + 1)
d[s[i]] = i
return maxlength
The results unsatisfactory, because the generated accounting dictionary memory, this will be time consuming to find
Find with index
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s: return 0
maxlength = 0
sub = ''
for i in range(len(s)):
if s[i] not in sub:
sub += s[i]
else:
idx = sub.index(s[i])
sub = sub[idx+1:] + s[i]
maxlength = max(maxlength, len(sub))
return maxlength
Fast very much, it turns out python comes with a function that is relatively easy to use LOL ...