0

LeetCode Question #3

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Input: "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

var lengthOfLongestSubstring = function(s) {
  var arr = s.split("");
  var fArr = [arr[0]];
  var x = fArr.length;
  
  for (var i = 1; i < arr.length; i++) {
    for (var j = i - 1; j < x; j++) {
      if (arr[i] !== fArr[j]) {
        fArr = [fArr[j] + arr[i]]; //fArr=['ab']
        x = fArr[j].length;
      } else {
        fArr.push(',');
        fArr.push(arr[i]);
      }
    }
  }
  
  console.log(fArr);
};

lengthOfLongestSubstring("abcabcbb");

I want to vary the x = fArr[j].length each time executing the for loop, so it may base on updated fArr length to run all the element in fArr, but it shows "Uncaught TypeError: Cannot read property 'length' of undefined", can anyone know why?

Andreas
  • 21,535
  • 7
  • 47
  • 56
auntR
  • 150
  • 1
  • 2
  • 15
  • The function `lengthOfLongestSubstring` produces a different error with the given input: `TypeError: fArr[j] is undefined` – Andreas Mar 06 '20 at 13:56
  • After you say `fArr = [fArr[j] + arr[i]]`, `fArr` has a single element and `x` is no longer the actual length. There's no need to have an extra variable `x` to keep track of the array length. `fArr.length` already does that. – M Oehm Mar 06 '20 at 14:29

0 Answers0