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.
Example 4:
Input: s = ""
Output: 0
Constraints:
s.length
<= 5 * 104s
consists of English letters, digits, symbols and spaces.๋ฌธ์๋ณ ๊ฐฏ์๋ฅผ ๋์ ๋๋ฆฌ๋ก ๋ง๋ค๊ณ ,
ํฌ ํฌ์ธํฐ
์๊ณ ๋ฆฌ์ฆ์ผ๋ก ๊ตฌ๊ฐ ๊ฒ์ฌ๋ฅผ ํ๋ฉด ๋๊ฒ ๋ค.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
mp = {x:0 for x in s}
l,r = 0,0
n = len(s)
res = 0
while r < n:
mp[s[r]] += 1
while mp[s[r]] > 1:
mp[s[l]] -= 1
l += 1
res = max(res, r-l+1)
r += 1
return res
O(2n)์ O(n)์ผ๋ก ์ค์ธ ์ฝ๋๋ค.
์ค๋ณต ๋ฌธ์๊ฐ ๋ฐ๊ฒฌ๋ ์๊ฐ, ์ฌ์ด์ ์๋ ๋ค๋ฅธ ์ค๋ณต ๋ฌธ์๋ฅผ ํฌํจํด์ ๊ตฌํ ์ ์๋ ์ต๋ ๊ธธ์ด๋ ์ด๋ฏธ ๊ตฌํด์ง ๊ฒ์ด๋ค. ๊ณ ๋ก left index ๋ฅผ right index๊ฐ ์๋ ๊ณณ๊น์ง ํ๋์ฉ ๋๋ ค๋ดค์ ํด๋ ๊ฐฑ์ ๋์ง ์๋๋ค.
์ด ์ ์ ๋ฐ์ํ์ฌ Solution 1
์ฝ๋๋ฅผ ์ต์ ํํด๋ณด์.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
mp = {x:None for x in s}
l,r = 0,0
n = len(s)
res = 0
while r < n:
idx = mp[s[r]]
if idx != None and l<=idx<r:
l = idx+1
res = max(res, r-l+1)
mp[s[r]] = r
r += 1
return res