【剑指offer】面试题50:(字符流中)第一个只出现一次的字符【C++版本】

总结的部分题目思路与代码,待完善。
【剑指offer-第二版】部分题目与解答【C++版本】

题目:字符串中第一个只出现一次的字符。

在字符串中找出第一个只出现一次的字符。如输入 " a b a c c d e f f " ,则输出 b

解题思路:

1.使用哈希表来记录每个字符出现的次数,因为字符 c h a r 为8位,总共有256个值,所有哈希表有256个元素,其中把字符的 A S C I I 码作为哈希表的键值,而对应键值储存的是该字符出现的次数。
2.那么对给定的字符串进行两次遍历,第一遍收集信息,即统计每个字符串出现了多少次。第二次查找第一个出现一次的字符,即碰到第一个只出现了一次的字符就进行输出。


哈希表是一种常用的数据结构,这里我们使用哈希表把一个字符映射成一个数字。在STL中,map和unordered_map就实现了哈希表的功能,同样使用数组/vector来实现简单的哈希表。

可以AC的代码【C++版本】

注意:牛客网上的接口要求返回的是第一次只出现一次的字符的位置,所以和剑指offer上略有不同

#include <vector>                            
#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>

using namespace std;

int FirstNotRepeatingChar(string str)
{
    int strSize = str.size();
    //处理错误输入
    if(strSize <= 0)return -1;
    //处理特殊输入
    if(strSize == 1)return 0;

    //使用vector做一个哈希表,记录每个字符出现的次数,全部初始化为0
    vector<int> hashTable(256,0);
    //范围for循环对输入字符串进行第一次遍历,统计每一种字符出现的次数
    for(auto s:str){
        hashTable[s]++;
    }

    //对输入字符串进行第二次遍历
    for(int i = 0;i != strSize;i++){
        if(hashTable[str[i]] == 1)
            return i;
    }

    return -1;
}

int main()
{
    cout << "Please enter a string:" << endl;
    string test;
    while(cin >> test){
        cout << FirstNotRepeatingChar(test) << endl;
    }

    return 0;
}

相关题目:字符流中第一个只出现一次的字符

1.因为是字符流,所以字符只能一个接着一个从字符流中读出来。
2.仍然使用哈希表来解决,这次哈希表中不记录字符出现的次数,而是记录只出现一次的字符首次出现的位置,哈希表中的元素全部初始化为-1,记录只出现一次的元素出现的位置,如果出现一次以上则置为-2。因此,每次遍历哈希表就能找到第一个只出现一次的字符

#include <limits.h>               
#include <vector>
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
#include <stdlib.h>

using namespace std;

//因为是字符流,所以只能一个一个从字符流中读出来
//仍然使用哈希表来解决
class charStatistics
{
    public:
        //构造函数
        charStatistics():index(0){
            for(int i = 0;i != 256;i++){
                hashTable[i] = -1;
            }
        }

        //从字符流中提取一个字符,并更新哈希表
        void Insert(char ch)
        {
            if(hashTable[ch] == -1){
                hashTable[ch] = index;
            }
            else if(hashTable[ch] >= 0){
                hashTable[ch] = -2;
            }

            index++;
        }

        //遍历哈希表,返回第一个只出现一次的字符
        char FirstAppearingOnce(){
            int fstPosi = INT_MAX;
            char resu = '#';
            for(int i = 0;i != 256;i++){
                if(hashTable[i] >= 0){
                    if(hashTable[i] < fstPosi){
                        fstPosi = hashTable[i];
                        resu = (char)i;
                    }
                }
            }

            return resu;
        }

    private:
        //哈希表
        vector<int> hashTable;
        //当前从数据流中提取的字符的个数
        int index;
};

猜你喜欢

转载自blog.csdn.net/m0_37950361/article/details/80666534