Posted onEdited onInLeetCodeDisqus: Symbols count in article: 670Reading time ≈1 mins.
hashmap O(n) 这个方法比简单统计字母频要快
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intfirstUniqChar(string s){ int f[26] = {0}; for (constauto &c : s) { ++f[c - 'a']; } int n = s.length(); for (int i = 0; i < n; ++i) { if (f[s[i] - 'a'] == 1) { return i; } } return-1; } };
把重复的字母的下标全部记成n,不重复的则记成i,然后遍历找出最小的i
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intfirstUniqChar(string s){ vector<int> m(26, INT_MAX); int n = s.length(); for (int i = 0; i < n; ++i) { int k = s[i] - 'a'; if (m[k] == INT_MAX) { m[k] = i; } elseif (m[k] < n) { m[k] = n; } } int res = *min_element(m.begin(), m.end()); return res < n ? res : -1; } };