# 387-First Unique Character in a String ###### tags: `Easy` ## Question https://leetcode.com/problems/first-unique-character-in-a-string/ ## Solution * 要得到原字串的第一個未重複自元,所以用unordered map,因為他不會再對字元的出現次數進行排序,所以第一個出現次數為1的字元就是答案(如果有需要排序的情況就是用map) ### C++ solution ```cpp= class Solution { public: int firstUniqChar(string s) { int n = s.length(); unordered_map<char,int> map; for(int i = 0; i < n ; i++) { map[s[i]]++; } for(int i = 0 ; i<n ; i++) { if(map[s[i]] == 1) { return i; } } return -1; } }; ``` ### kyle's solution 想法一: 用一個map紀錄次數,用另一個map紀錄第一個出現的char,再用一個set紀錄想刪掉的char... 用的有點多space ```cpp= #include <map> using namespace std; int firstNonRepeatingCharacter(string string) { // Write your code here. map<char, int> check; map<int, char> sorted_fnpc; unordered_set<char> to_del_items; for (int i=0; i < string.size(); i++){ if (check.count(string[i]) == 0){ check.insert({string[i], i}); sorted_fnpc.insert({i, string[i]}); }else to_del_items.insert(check[string[i]]); } for (char x: to_del_items) { sorted_fnpc.erase(x); } if (sorted_fnpc.empty()) return -1; else return sorted_fnpc.begin()->first; } ``` 較優解:一個迴圈紀錄次數,一個迴圈看第一個只出現一次的子母 *值得注意的是子母最多就26個所以是 O(1) space 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up