387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
# @param {String} s
# @return {Integer}
def first_uniq_char(s)
return -1 if s.chars.empty?
hash = Hash[s.chars.group_by{|x| x}.map{|k,v|[k,v.size]}]
arr = hash.select{|k,v| v == 1}
if arr.empty?
-1
else
s.index(arr.first[0])
end
end
Last updated
Was this helpful?