.Zzumbong

[leetCode/JS] 3. Longest Substring Without Repeating Characters 본문

coding test/leetCode

[leetCode/JS] 3. Longest Substring Without Repeating Characters

쭘봉 2022. 11. 23. 11:09

문제 설명

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.

내 솔루션

  • 반복되는 글자들 중 중복되지 않은 가장 긴 문자열 찾기
  • 그나마 좀 실용적인 문제라서 재미 있었다.
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  let word = [];
  let longest = 0;
  for(let str of s.split('')) {
    const idx = word.indexOf(str);
    if(idx > -1) {
      // 중복되는 글자를 찾았으면 longest 업데이트
      longest = Math.max(longest, word.length);
      // 중복된 string은 버린다.
      word.splice(0, idx + 1);
    }
    word.push(str);
  }
  return Math.max(longest, word.length);
};

감상평

  • 몬가 좀 더 직관적으로 표현 할 수 있을 것 같은데..
Comments