728x90
3. Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
Examples
1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 10^4
s
consists of English letters, digits, symbols and spaces.
Python solution
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
used = dict()
max_length = start = 0
for i, c in enumerate(s):
if c in used and start <= used.get(c):
start = used.get(c) + 1
else:
max_length = max(max_length, i - start + 1)
used[c] = i
return max_length
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[Python] Longest Palindromic Substring - LeetCode (0) | 2021.09.23 |
---|---|
[Python] Median of Two Sorted Arrays - LeetCode (0) | 2021.09.16 |
[Python] Add Two Numbers - LeetCode (0) | 2021.09.16 |
[Python] Two Sum - LeetCode (0) | 2021.09.16 |
댓글