JSFiddle - React, Tailwind, and code Playground

by dumptyd

JavaScript

console.log = (...args) => {
	args.forEach(arg => document.querySelector('pre').innerText += (arg + ' '));
	document.querySelector('pre').innerText += '\n';
};

/**
 * @param {string} s
 * @return {number}
 */
const lengthOfLongestSubstring = (str) => {
  let maxLength = 0,
    windowStart = 0,
    charIndexMap = {};

  for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
    const rightChar = str[windowEnd];

    if (rightChar in charIndexMap) {
    	console.log(windowStart, charIndexMap[rightChar] + 1);
      windowStart = Math.max(windowStart, charIndexMap[rightChar] + 1);
    }

    charIndexMap[rightChar] = windowEnd;

    maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
  }

  return maxLength;
};

const inputs = [
  "abcabcbb",
  "bbbbb",
  "pwwkew",
  "",
  " ",
  "a",
  "tmmzuxt"
].slice(6)

inputs.forEach(input => {

	console.log('Input: ', input);
  console.log('Output: ', lengthOfLongestSubstring(input));
  console.log('---------------');
})