字符流中的第一个不重复的字符

本文介绍了一种使用哈希表统计字符流中每个字符出现次数的方法,并提供了C++和Python的实现代码。通过实时更新哈希表,可以高效地找出字符流中首次出现的非重复字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&tPage=3&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路:建立哈希表统计每个字符出现的次数即可



class Solution
{
public:
	string s;//储存当前的字符流
	int hashtable[256];
	Solution ()//用构造函数初始化
	{
		s = "";
		for(int i = 0; i < 256; i++)
			hashtable[i] = 0;
	}
  //Insert one char from stringstream
    void Insert(char ch)
    {
         hashtable[ch]++;
		 s += ch;//拼接当前的字符串
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
		int len = s.size();
		for(int i = 0; i < len ;i++)//找到字符串中第一个不重复出现的字符
		{
			if(hashtable[s[i]] == 1)
				return s[i];
		}
		return '#';
    
    }

};

 

Python 实现


class Solution:
    # 返回对应char
    def __init__(self):
        self.res = []
    def FirstAppearingOnce(self):
        if not self.res:
            return '#'
        return self.res[0]
    def Insert(self, char):
        if char in self.res:
           self.res.remove(char)##重复的就移走
        else:
            self.res.append(char)##不重复的就加入列表

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值