Ruby 2 Lines


  • 0
    I
    # @param {String} s
    # @return {Integer}
    # built in functions
    def first_uniq_char_built_in_functions(s)
        result = Hash[s.chars.group_by {|item| item}.map {|key, value| [key, value.count]}]
        return result.key(1).nil?? -1 : s.chars.index(result.key(1))
    end
    
    # @param {String} s
    # @return {Integer}
    # non built in functions
    def first_uniq_char(s)
        result  = Hash.new
        s.chars.each_with_index do |char,index|
            result[char.to_sym] = result[char.to_sym].nil?? {count:1,first_index:index} : {count:result[char.to_sym][:count]+1,first_index:result[char.to_sym][:first_index]}
        end
        result.each do |key, value|
            if value[:count] == 1
                return value[:first_index]
            end
        end
        return -1
    end
    

Log in to reply
 

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