LeetCode-Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: s = "abcabcbb" 
Output: 3
Explanation: The answer is "abc", with the length of 3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:

dic, res, start, = {}, 0, 0
for i, ch in enumerate(s):
# when char already in dictionary
if ch in dic:
# check length from start of string to index
res = max(res, i-start)
# update start of string index to the next index
start = max(start, dic[ch]+1)
# add/update char to/of dictionary
dic[ch] = i
# answer is either in the begining/middle OR some mid to the end of string
return max(res, len(s)-start)

© 2022 Tiffany's Blog All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero