387. 字符串中的第一个唯一字符
题目来源:387. 字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
/** * @param {string} s * @return {number} */ var firstUniqChar = function(s) { const frequency = new Map(); for(let c of s){ frequency.set(c, (frequency.get(c) || 0)+1); } for (const [i, ch] of Array.from(s).entries()) { if (frequency.get(ch) === 1) { return i; } } return -1; };
示例:
s = "leetcode" 返回 0 s = "loveleetcode" 返回 2
Python3
import collections class Solution: def firstUniqChar(self, s: str) -> int: fr = collections.Counter(s) for i,c in enumerate(s): if fr.get(c) == 1: return i return -1 # dic = dict() # for c in s: # dic[c] = dic.get(c, 0) + 1 # index = 0 # for [key, val] in dic.items(): # if val == 1: # return index # index += 1 # return -1 if __name__ == '__main__': so = Solution() s = "leetcode" print(so.firstUniqChar(s)) s = "loveleetcode" print(so.firstUniqChar(s))
提示:你可以假定该字符串只包含小写字母。