Leetcode.js: Longest Substring Without Repeating Characters

May 19, 2018, 1 min read

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Explaining:

用一個 prevShown 紀錄此字元 c 上次出現是什麼時候, 用 start 代表答案 substring 的頭,

如果 start 比 c 上一次出現的 index 小, 更新 start 為 map[c],

然後每次 for 迴圈更新 maxLen 值。

Solution:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  if (s.length <= 1) return s.length;

  let maxLen = 0;
  let start = 0;

  let prevShown = {};
  s.split('').forEach((c, i) => {
    if (c in prevShown && start <= prevShown[c]) {
      start = prevShown[c] + 1;
    }

    prevShown[c] = i;

    maxLen = Math.max(maxLen, i - start + 1);
  });

  return maxLen;
};

Category leetcode.js

Tags leetcode, js

Comments