时间复杂度:O(n) n 表示字符串 str 的长度。 空间复杂度:O(Σ) 其中 Σ 是字符集,由于本题中 s 只包含大小写字母,因此 Σ <= 52。 */ classSolution { public: intFirstNotRepeatingChar(string str){ vector<int> count(58, 0); for (int i = 0; i < str.size(); i ++) { count[str[i] - 'A'] += 1; } for (int i = 0; i < str.size(); i ++) { if (count[str[i] - 'A'] == 1) return i; }
return-1; } };
/* 哈希表:unordered_map
时间复杂度:O(n) 空间复杂度:O(Σ) */ classSolution { public: intFirstNotRepeatingChar(string str){ unordered_map<char, int> ch2cnt; for (int i = 0; i < str.size(); i ++) { ch2cnt[str[i]] += 1; } for (int i = 0; i < str.size(); i ++) { if (ch2cnt[str[i]] == 1) return i; }