public class Solution { public int FirstUniqChar(string s) { Dictionary<char, int> dic = new Dictionary<char, int>(); foreach (char c in s) { if (!dic.ContainsKey(c)) { dic.Add(c, 1); } else { dic[c]++; } } var list = dic.Where(x => x.Value == 1).ToList(); var index = -1; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (list.Any(x => x.Key == c)) { index = i; break; } } Console.WriteLine(index); return index; } }
https://leetcode.com/problems/first-unique-character-in-a-string/#/description
补充一个python的实现:
1 import collections 2 3 class Solution: 4 def firstUniqChar(self, s: str) -> int: 5 dic = collections.OrderedDict()#有序字典 6 for i in range(len(s)):#遍历字符串 7 c = s[i]#当前字符 8 if c not in dic:#第一次出现,key是字符,value是一个二元组[字符频率,字符索引] 9 dic[c] = [1,i] 10 else: 11 dic[c][0] += 1#出现多次,key是字符,value二元组修改,字符频率+1 12 dic[c][1] = -1#字符索设定为-1,表示此字符不符合题目要求 13 for _,v in dic.items():#dic有序 14 if v[0] == 1:#字符出现了一次 15 return v[1]#返回对应的索引 16 return -1