ES6 O(n) beats 81%


  • 0
    Y
    function longestDistinctSubstring(string) {
      if (!string.length) {
        return 0
      }
      let substringStart = 0
      let substringLength = 1
      const indexByCharacter = new Map()
      for (let i = 0; i < string.length; i++) {
        const currentCharacter = string.charAt(i)
        const j = indexByCharacter.get(currentCharacter)
        if (
          j !== undefined &&
          j >= substringStart
        ) {
          substringStart = j + 1
        }
        indexByCharacter.set(currentCharacter, i)
        substringLength = Math.max(substringLength, i - substringStart + 1)
      }
      return substringLength
    }
    

Log in to reply
 

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