๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 3 - Longest Substring Without Repeating Characters (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 3๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ค‘๋ณต๋œ ๋ฌธ์ž๊ฐ€ ์—†๋Š” ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ์ค‘์—์„œ ๊ฐ€์žฅ ๊ธธ์ด๊ฐ€ ๊ธด ๊ฒƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ head, tail ๋ฅผ ํ™œ์šฉํ•ด์„œ ์œˆ๋„์šฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๊ณ  ์ค‘๋ณต๋œ ๋ฌธ์ž๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด
ํ˜„์žฌ ์œˆ๋„์šฐ์—์„œ ์ค‘๋ณต๋œ ๋ฌธ์ž์˜ ์œ„์น˜๋กœ head ๋ฅผ ์ด๋™์‹œํ‚ค๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
  const cache = new Map();
  let head = 0;
  let tail = 0;
  let answer = 0;

  for (; tail < s.length; tail++) {
    if (cache.has(s[tail])) {
      const duplicateIndex = cache.get(s[tail]);

      for (let i = head; i < duplicateIndex; i++) {
        cache.delete(s[i]);
      }

      answer = Math.max(answer, tail - head);
      head = duplicateIndex + 1;
    }

    cache.set(s[tail], tail);
  }

  answer = Math.max(answer, tail - head);

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 494 - Target Sum (Medium)  (0) 2021.03.04
LeetCode 187 - Repeated DNA Sequences (Medium)  (0) 2021.03.03
LeetCode 89 - Gray Code (Medium)  (0) 2021.03.03
LeetCode 118 - Pascal's Triangle (Easy)  (0) 2021.03.03
LeetCode 19 - Remove Nth Node From End of List (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€