zerovoids.dev
LEETCODEMedium

Longest Substring Without Repeating Characters

풀이일 2025 · 03 · 17기록 3 ms · 58.9 MB원문 leetcode ↗
Hash TableStringSliding Window
문제

Given a string s, find the length of the longest substring without duplicate characters.

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.

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 <= 105
  • s consists of English letters, digits, symbols and spaces.
풀이 TypeScript
function lengthOfLongestSubstring(s: string): number {
  if (!s) return 0;

  const charPosition = new Map<string, number>();
  let maxLength = 0;
  let start = 0;

  s.split('').forEach((char, currentPos) => {
    const lastPosition = charPosition.get(char);

    if (lastPosition !== undefined && lastPosition >= start) {
      start = lastPosition + 1;
    } else {
      maxLength = Math.max(maxLength, currentPos - start + 1);
    }

    charPosition.set(char, currentPos);
  })
  return maxLength;
}
복사됨