Skip to content

387. First Unique Character in a String

https://leetcode.com/problems/first-unique-character-in-a-string/

js
/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
  const map = {}
  s.split('').forEach(c => {
    map[c] = (map[c] || 0) + 1
  })

  for (let i = 0; i < s.length; i++) {
    if (map[s[i]] === 1) {
      return i
    }
  }

  return -1
}
py
class Solution:

    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        m = {}
        for c in s:
            m[c] = m.get(c, 0) + 1
        for i in range(len(s)):
            if m[s[i]] == 1:
                return i
        return -1