剑指 Offer(第2版)面试题 50:第一个只出现一次的字符
剑指 Offer(第2版)面试题 50:第一个只出现一次的字符
题目一:字符串中第一个只出现一次的字符
题目来源:63. 字符串中第一个只出现一次的字符
第一次遍历,用哈希表记录字符及其出现的次数。
第二次遍历,当遍历的字符的出现次数为 1 时,返回该字符。
如果字符串中不存在只出现一次的字符,返回 ‘#’ 字符。
代码:
class Solution
{
public:
char firstNotRepeatingChar(string s)
{
if (s.empty())
return '#';
unordered_map<char, int> hash;
for (const char &c : s)
hash[c]++;
for (const char &c : s)
if (hash[c] == 1)
return c;
return '#';
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(n),其中 n 是字符串 s 的长度。
拓展题:LeetCode 387. 字符串中的第一个唯一字符
把字符换成下标就行。
代码:
/*
* @lc app=leetcode.cn id=387 lang=cpp
*
* [387] 字符串中的第一个唯一字符
*/
// @lc code=start
class Solution
{
public:
int firstUniqChar(string s)
{
if (s.empty())
return -1;
unordered_map<char, int> hash;
for (const char &c : s)
hash[c]++;
for (int i = 0; i < s.size(); i++)
if (hash[s[i]] == 1)
return i;
return -1;
}
};
// @lc code=end
复杂度分析:
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(n),其中 n 是字符串 s 的长度。
还有一种写法,有点绕,不推荐:
class Solution
{
public:
int firstUniqChar(string s)
{
unordered_map<int, int> position;
int n = s.size();
for (int i = 0; i < n; ++i)
{
if (position.count(s[i]))
{
position[s[i]] = -1;
}
else
{
position[s[i]] = i;
}
}
int first = n;
for (auto [_, pos] : position)
{
if (pos != -1 && pos < first)
{
first = pos;
}
}
if (first == n)
{
first = -1;
}
return first;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(n),其中 n 是字符串 s 的长度。
题目二:字符流中第一个只出现一次的字符
题目来源:64. 字符流中第一个只出现一次的字符
用一个哈希表 hash 存储出现字符和它的频数。
用一个队列 q 存储只出现一次的字符,队列有先进先出的特性,保证每次都能取到第一个只出现一次的字符。
insert(char ch):首先将 hash[ch]++
- 如果 hash[ch] > 1,说明不止出现一次,队列中一定有我们要弹出的元素(前提是队列不为空),将满足 hash[q.front()] > 1 的全部弹出。
- 否则,ch 是一个只出现一次的字符,将其插入队列。
firstAppearingOnce():队列的头就是第一个只出现一次的字符,如果队列为空,返回 ‘#’。
代码:
class Solution
{
private:
queue<char> q;
unordered_map<char, int> hash;
public:
// Insert one char from stringstream
void insert(char ch)
{
if (++hash[ch] > 1)
{
// 当新的字符已经重复,则不插入,而且将队首有可能重复的 pop 出来
while (!q.empty() && hash[q.front()] > 1)
q.pop();
}
else
q.push(ch);
}
// return the first appearence once char in current stringstream
char firstAppearingOnce()
{
if (!q.empty())
return q.front();
else
return '#';
}
};
复杂度分析:
时间复杂度:
-
insert(char ch):O(n),其中 n 是字符流的长度。
-
firstAppearingOnce():O(1)。
空间复杂度:O(n),其中 n 是字符流的长度。
文章详细解析了如何使用哈希表解决字符串和字符流中第一个只出现一次的字符问题,提供了三种不同的解题方法,并分析了它们的时间和空间复杂度。
229

被折叠的 条评论
为什么被折叠?



