code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

01 Longest Substring Without Repeating Characters

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const longestSubstringWithoutRepeatingCharacters = str => {
  let w = new Set()
  let left = 0
  let length = 0
  let max = 1
  for (let right = 0; right < str.length; right++) {
    if (w.has(str[right])) {
      while (w.has(str[right])) {
        w.delete(str[left])
        left += 1
      }
    }
    w.add(str[right])
    length = right - left + 1
    max = Math.max(length, max)
  }
  return max
}

console.log(longestSubstringWithoutRepeatingCharacters('abcabcbb'))

// test('longestSubstringWithoutRepeatingCharacters', () => {
//   expect(longestSubstringWithoutRepeatingCharacters("abcabcbb")).toEqual(3)
// });

Created 2022-02-04T04:03:39+00:00 · Edit