Leetcode :: Longest Substring Without Repeating Characters

์ˆ‘์ˆ‘ยท2021๋…„ 5์›” 12์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
91/122
post-thumbnail

Problem

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:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Guess

  • ๋ฌธ์ž๋ณ„ ๊ฐฏ์ˆ˜๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋งŒ๋“ค๊ณ ,

  • ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ๊ตฌ๊ฐ„ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๋ฉด ๋˜๊ฒ ๋‹ค.

Solution 1

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

Solution 2

O(2n)์„ O(n)์œผ๋กœ ์ค„์ธ ์ฝ”๋“œ๋‹ค.

์ค‘๋ณต ๋ฌธ์ž๊ฐ€ ๋ฐœ๊ฒฌ๋œ ์ˆœ๊ฐ„, ์‚ฌ์ด์— ์žˆ๋˜ ๋‹ค๋ฅธ ์ค‘๋ณต ๋ฌธ์ž๋ฅผ ํฌํ•จํ•ด์„œ ๊ตฌํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๊ธธ์ด๋Š” ์ด๋ฏธ ๊ตฌํ•ด์ง„ ๊ฒƒ์ด๋‹ค. ๊ณ ๋กœ left index ๋ฅผ right index๊ฐ€ ์žˆ๋Š” ๊ณณ๊นŒ์ง€ ํ•˜๋‚˜์”ฉ ๋Š˜๋ ค๋ดค์ž ํ•ด๋Š” ๊ฐฑ์‹ ๋˜์ง€ ์•Š๋Š”๋‹ค.
์ด ์ ์„ ๋ฐ˜์˜ํ•˜์—ฌ Solution 1 ์ฝ”๋“œ๋ฅผ ์ตœ์ ํ™”ํ•ด๋ณด์ž.

  • ๋งต์— ๋ฌธ์ž ์นด์šดํŠธ๊ฐ€ ์•„๋‹Œ, ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•œ๋‹ค.
  • ์ค‘๋ณต ๋ฌธ์ž ๋ฐœ๊ฒฌ ์‹œ left index๋ฅผ ์ค‘๋ณต ๋ฌธ์ž ๋ฐ”๋กœ ๋‹ค์Œ์œผ๋กœ ์˜ฎ๊ธด๋‹ค.
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

profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€