Javascript


  • 0
    H
    /**
     * @param {string} s
     * @return {number}
     */
    var firstUniqChar = function(s) {
      if (!s) return -1
      var result = {}
    
      for (var i = 0; i < s.length; i++) {
        if (result[s[i]]) {
          result[s[i]] = { occurence: result[s[i]].occurence + 1 }
        } else {
          result[s[i]] = { index: i, occurence: 1 }
        }
      }
    
      const occurences = Object.keys(result).filter(char => {
        if (result[char].occurence == 1) return result[char]
      })
    
      var index = -1
      if (!occurences.length) return -1
      index = result[occurences[0]].index
    
      for (i = 1; i < occurences.length; i++) {
        if (result[occurences[i]].index < index) index = result[occurences[i]].index
      }
    
      return index
    }
    

Log in to reply
 

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