剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)
生活随笔
收集整理的這篇文章主要介紹了
剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 題目
在字符串 s 中找出第一個(gè)只出現(xiàn)一次的字符。如果沒(méi)有,返回一個(gè)單空格。
示例: s = "abaccdeff" 返回 "b"s = "" 返回 " "限制: 0 <= s 的長(zhǎng)度 <= 50000來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
2. 解題
class Solution { public:char firstUniqChar(string s) {unordered_map<char,int> m;for(int i = 0; i < s.size(); ++i){if(m.count(s[i]))m[s[i]] = -1;//標(biāo)記為-1表示出現(xiàn)多次elsem[s[i]] = i;//存儲(chǔ)位置}int idx = INT_MAX;char ans = ' ';for(auto& mi : m){if(mi.second != -1 && mi.second < idx){idx = mi.second;ans = mi.first;}}return ans;} }; class Solution { public:char firstUniqChar(string s) {vector<int> count(128,-1);for(int i = 0; i < s.size(); ++i){if(count[s[i]] == -1)//-1表示沒(méi)有出現(xiàn)count[s[i]] = i;//存儲(chǔ)位置else//出現(xiàn)過(guò)count[s[i]] = -2;//表示重復(fù)}char ans = ' ';int idx = INT_MAX;for(int i = 0; i < 128; ++i)if(count[i] != -1 && count[i] != -2 && count[i] < idx){ans = i;idx = count[i];}return ans;} };總結(jié)
以上是生活随笔為你收集整理的剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode 1266. 访问所有点
- 下一篇: 程序员面试金典 - 面试题 05.01.