Find longest substring without repeating characters

前端 未结 30 2564
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  长情又很酷
    2020-12-12 19:01

    This is my solution, and it was accepted by leetcode. However, after I saw the stats, I saw whole lot solutions has much faster result....meaning, my solution is around 600ms for all their test cases, and most of the js solutions are around 200 -300 ms bracket.. who can tell me why my solution is slowwww??

    var lengthOfLongestSubstring = function(s) {
      var arr = s.split("");
    
      if (s.length === 0 || s.length === 1) {
        return s.length;
      }
    
      var head = 0,
        tail = 1;
      var str = arr[head];
      var maxL = 0;
      while (tail < arr.length) {
        if (str.indexOf(arr[tail]) == -1) {
          str += arr[tail];
          maxL = Math.max(maxL, str.length);
          tail++;
        } else {
          maxL = Math.max(maxL, str.length);
          head = head + str.indexOf(arr[tail]) + 1;
          str = arr[head];
          tail = head + 1;
        }
      }
      return maxL;
    };

提交回复
热议问题