12-line JavaScript O(n) simple solution, 148ms 97.14%


  • 0
    K
    /**
     * @version 0.3
     * @param {string} s
     * @return {number}
     */
    function lengthOfLongestSubstring(s) {
      let length = s.length;
      let subArray = [];
      let max = 0;
      for (let i = 0; i < length; i++) {
        let index = subArray.indexOf(s[i]);
        // Find char at subArray[index]
        if (index >= 0) {
          // Cut old sub string
          subArray.splice(0, index + 1);
        }
        subArray.push(s[i]);
        max = subArray.length >= max ? subArray.length : max;
      }
      return max;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.