算法学习七----在一个字符串中找到第一个只出现一次的字符

本文介绍了一种在字符串中快速找到第一个仅出现一次字符的算法。通过使用映射表数据结构,该算法扫描字符串并记录每个字符的出现次数,最终返回首次出现的单一字符。

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

题目:在一个字符串中找到第一个只出现一次的字符。
如输入abaccdeff,则输出b。  
算法思路:
此算法的实现在于选择适当的数据结构,可以选择一种叫映射表的数据结构
映射表简单地说就是进化的“数组”,但是“数组”的下标可以是任意类型
所以可以选择字符与数字的映射表作为数据结构,然后扫描字符串的每一个字符,如果当前字符还没有在映射表中,则添加进去映射表,并将其值设为1,反之,则将该值对应的值加1

算法的伪代码

create map<char, int>

//scan the string,

for i <- 1 to s.length

     if char is already existed in the map
          then add its count
     else assign 1 to the map

for begin <- m.begin() to m.end()
     if found first not repeating char
          then return its char

C++实现

//find first char that appear once in the string
char FirstNotRepeatingChar(const string &s)
{
    //create map<char, int>
    map<char, int> m;

    //scan the string
    for(int i = 0; i != s.length(); ++i)
    {
        //if char is already existed in the map
        if(m[s[i]])
        {
            //then add its count
            ++m[s[i]];
        }
        else
        {
            //else assign 1 to the map
            m[s[i]] = 1;
        }
    }

    //for begin <- m.begin() to m.end()
    for(auto begin = m.begin(); begin != m.end(); ++begin)
    {
        //if found first not repeating char
        if(begin->second == 1)
        {
            //then return its char
            return begin->first;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值