JS solution O(n) -- scan the string twice


  • 0
    E
    /**
     * @param {string} s
     * @return {number}
     */
    var firstUniqChar = function (s) {
        'use strict';
        var seen = {};
        var i;
        for (i = 0; i < s.length; i += 1) {
            if (seen[s.charAt(i)] === undefined) {
                seen[s.charAt(i)] = 1;
            } else {
                seen[s.charAt(i)] += 1;
            }
        }
        var unique = -1;
        for (i = 0; i < s.length; i += 1) {
            if (seen[s.charAt(i)] === 1) {
                unique = i;
                break;
            }
        }
        return unique;
    };
    

Log in to reply
 

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