![微信公众号:路人zhang](https://image.mianshi.online/img202209102100234.png)
扫码关注微信公众号
回复“面试手册”,获取本站PDF版
回复“简历”,获取高质量简历模板
回复“加群”,加入程序员交流群
回复“电子书”,获取程序员类电子书
题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
输入:s = "abaccdeff"
输出:'b'
示例 2:
输入:s = ""
输出:' '
限制:
0 <= s 的长度 <= 50000
算法
(哈希表) O(n)
- 遍历一遍字符串用哈希表存储每个字符出现的次数
- 再遍历一遍字符串遇到只出现一次的字符返回即可,否则返回
#
时间复杂度
字符串被遍历两次,时间复杂度为 O(n)
空间复杂度
O(n)
C++ 代码
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<char, int> cnt;
for (auto c : s) cnt[c] ++ ;
for (auto c : s)
if (cnt[c] == 1)
return c;
return ' ';
}
};
Java 代码
class Solution {
public char firstUniqChar(String s) {
HashMap<Character, Integer> cnt = new HashMap<>();
for (char c : s.toCharArray()) {
cnt.put(c, cnt.getOrDefault(c, 0) + 1);
}
for (char c : s.toCharArray()) {
if (cnt.get(c) == 1) {
return c;
}
}
return ' ';
}
}
Python 代码
class Solution:
def firstUniqChar(self, s: str) -> str:
cnt = {}
for c in s:
cnt[c] = cnt.get(c, 0) + 1
for c in s:
if cnt[c] == 1:
return c
return ' '
本文由读者提供,Github地址:https://github.com/tonngw
点击面试手册,获取本站面试手册PDF完整版