面试题50:第一个只出现一次的字符(C++)
2021-02-17 21:17
标签:strong 直接 char for order 一个 sof 空格 https 题目地址:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/ 在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 示例: 思路1:利用哈希表统计每个字符出现的次数,如果该字符出现的次数为1次,则直接返回。具体分为两步,第一步是将字符串s中每个字符出现的次数存储到哈希表中,第二步是遍历哈希表,将出现1次的字符返回。 思路2:数组优化哈希表 哈希表 数组优化哈希表 面试题50:第一个只出现一次的字符(C++) 标签:strong 直接 char for order 一个 sof 空格 https 原文地址:https://www.cnblogs.com/wzw0625/p/12696080.html题目描述
题目示例
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
解题思路
程序源码
class Solution {
public:
char firstUniqChar(string s) {
if(s.size() == 0) return ‘ ‘;
unordered_mapchar, int> mp;
for(int i = 0; i )
{
mp[s[i]]++;
}
for(int j = 0; j )
{
if(mp[s[j]] == 1) return s[j];
}
return ‘ ‘;
}
};
class Solution {
public:
char firstUniqChar(string s) {
if(s.size() == 0) return ‘ ‘;
vectorint> arr(26, 0);
for(int i = 0; i )
{
arr[s[i] - ‘a‘]++;
}
for(int j = 0; j )
{
if(arr[s[j] - ‘a‘] == 1) return s[j];
}
/*for(char c:s)
{
arr[c - ‘a‘]++;
}
for(char c:s)
{
if(arr[c - ‘a‘] == 1) return c;
}*/
return ‘ ‘;
}
};
文章标题:面试题50:第一个只出现一次的字符(C++)
文章链接:http://soscw.com/index.php/essay/56737.html