classSolution { public: intfirstUniqChar(string s){ unordered_map<int, int> frequency; for (char ch: s) { ++frequency[ch]; } for (int i = 0; i < s.size(); ++i) { if (frequency[s[i]] == 1) { return i; } } return-1; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintfirstUniqChar(String s) { Map<Character, Integer> frequency = newHashMap<Character, Integer>(); for (inti=0; i < s.length(); ++i) { charch= s.charAt(i); frequency.put(ch, frequency.getOrDefault(ch, 0) + 1); } for (inti=0; i < s.length(); ++i) { if (frequency.get(s.charAt(i)) == 1) { return i; } } return -1; } }
[sol1-Python3]
1 2 3 4 5 6 7
classSolution: deffirstUniqChar(self, s: str) -> int: frequency = collections.Counter(s) for i, ch inenumerate(s): if frequency[ch] == 1: return i return -1
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9
var firstUniqChar = function(s) { const frequency = _.countBy(s); for (const [i, ch] ofArray.from(s).entries()) { if (frequency[ch] === 1) { return i; } } return -1; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12
funcfirstUniqChar(s string)int { cnt := [26]int{} for _, ch := range s { cnt[ch-'a']++ } for i, ch := range s { if cnt[ch-'a'] == 1 { return i } } return-1 }
classSolution { publicintfirstUniqChar(String s) { Map<Character, Integer> position = newHashMap<Character, Integer>(); intn= s.length(); for (inti=0; i < n; ++i) { charch= s.charAt(i); if (position.containsKey(ch)) { position.put(ch, -1); } else { position.put(ch, i); } } intfirst= n; for (Map.Entry<Character, Integer> entry : position.entrySet()) { intpos= entry.getValue(); if (pos != -1 && pos < first) { first = pos; } } if (first == n) { first = -1; } return first; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: deffirstUniqChar(self, s: str) -> int: position = dict() n = len(s) for i, ch inenumerate(s): if ch in position: position[ch] = -1 else: position[ch] = i first = n for pos in position.values(): if pos != -1and pos < first: first = pos if first == n: first = -1 return first
funcfirstUniqChar(s string)int { n := len(s) pos := [26]int{} for i := range pos[:] { pos[i] = n } for i, ch := range s { ch -= 'a' if pos[ch] == n { pos[ch] = i } else { pos[ch] = n + 1 } } ans := n for _, p := range pos[:] { if p < ans { ans = p } } if ans < n { return ans } return-1 }