longest-substring-without-repeating-characters
This commit is contained in:
parent
60066617e3
commit
b904a8bb91
@ -0,0 +1,30 @@
|
|||||||
|
Given a string `s`, find the length of the **longest substring** without repeating characters.
|
||||||
|
|
||||||
|
**Example 1:**
|
||||||
|
|
||||||
|
Input: s = "abcabcbb"
|
||||||
|
Output: 3
|
||||||
|
Explanation: The answer is "abc", with the length of 3.
|
||||||
|
|
||||||
|
|
||||||
|
**Example 2:**
|
||||||
|
|
||||||
|
Input: s = "bbbbb"
|
||||||
|
Output: 1
|
||||||
|
Explanation: The answer is "b", with the length of 1.
|
||||||
|
|
||||||
|
|
||||||
|
**Example 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.
|
||||||
|
|
||||||
|
|
||||||
|
**Constraints:**
|
||||||
|
|
||||||
|
* `0 <= s.length <= 5 * 104`
|
||||||
|
* `s` consists of English letters, digits, symbols and spaces.
|
||||||
|
|
||||||
|
https://leetcode.com/problems/longest-substring-without-repeating-characters
|
@ -0,0 +1,29 @@
|
|||||||
|
# Time: O(N)
|
||||||
|
# Space: O(N)
|
||||||
|
class Solution:
|
||||||
|
def lengthOfLongestSubstring(self, s: str) -> int:
|
||||||
|
'''
|
||||||
|
Sliding-window approach
|
||||||
|
'''
|
||||||
|
|
||||||
|
# Keep a track of unique chars we've seen so far in the substring
|
||||||
|
# we are looking at
|
||||||
|
seen = set()
|
||||||
|
start, end = 0, 0
|
||||||
|
maxl = 0
|
||||||
|
|
||||||
|
while start <= end < len(s):
|
||||||
|
# Our current substring is denoted by their bounds [start, end]
|
||||||
|
# If we see a char in `end` which is already seen by us, we need
|
||||||
|
# to keep moving `start` until we are left with a new character
|
||||||
|
while s[end] in seen:
|
||||||
|
# Since `start` is moving up, we need to remove existing
|
||||||
|
# `start` char from the set if it exists
|
||||||
|
seen.remove(s[start])
|
||||||
|
start += 1
|
||||||
|
|
||||||
|
seen.add(s[end])
|
||||||
|
maxl = max(maxl, (end - start) + 1)
|
||||||
|
end += 1
|
||||||
|
|
||||||
|
return maxl
|
Loading…
Reference in New Issue
Block a user