剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)
生活随笔
收集整理的這篇文章主要介紹了
剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
在字符串 s 中找出第一個只出現一次的字符。如果沒有,返回一個單空格。
示例: s = "abaccdeff" 返回 "b"s = "" 返回 " "限制: 0 <= s 的長度 <= 50000來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
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;//標記為-1表示出現多次elsem[s[i]] = i;//存儲位置}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表示沒有出現count[s[i]] = i;//存儲位置else//出現過count[s[i]] = -2;//表示重復}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;} };總結
以上是生活随笔為你收集整理的剑指Offer - 面试题50. 第一个只出现一次的字符(unordered_map)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1266. 访问所有点
- 下一篇: 程序员面试金典 - 面试题 05.01.