剑指offer—字符流中第一个不重复的字符

来源:互联网 发布:淘宝拍a发b不降权 编辑:程序博客网 时间:2024/04/28 04:26

华电北风吹
天津大学认知计算与应用重点实验室
日期:2015/10/8

题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。

解析:用一个数组记录每个字符出现的次数,再用另一个数组记录每个字符出现的位置。

class Solution{public:    Solution()    {        memset(count, 0, sizeof(count));        memset(order, 0, sizeof(order));    }    int count[256];    int order[257];    int k = 0;    //Insert one char from stringstream    void Insert(char ch)    {        count[ch]++;        k++;        order[ch] = k;    }    //return the first appearence once char in current stringstream    char FirstAppearingOnce()    {        order[256] = k+1;        int result = 256;        for (int i = 0; i<256; i++)            if ((count[i] == 1) && (order[i]<order[result]))                result = i;        return result == 256 ? '#' : result;    }};
0 0
原创粉丝点击