• 【面试题035】第一个只出现一次的字符


    【面试题035】第一个只出现一次的字符
    题目:
        在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出‘b’。
     
    思路一:
        从头遍历字符串,每遍历一个字符就和后面的字符做比较,如果没有发现后面出现相同的字符,那么这个时候还挺复杂的,
    例如上面的字符串,第一个a发现后面有a,但是第二个a,发现后面没有a,起始得重头到位做判断,而且得判断前面有没有
    出现过。
     
    思路二:
        定义哈希表的键值(key)是字符,而值(value)是该字符出现的次数。
    ——C++的标准库中没有实现哈希表,
        第一次扫描字符串,在key对应的的value上面加一(当然初始值都是0)
        第二次扫面字符串,每扫描到一个字符就能从哈希表中得到该字符出现的次数,那么第一个只出现一次的字符就是符合要求的输出。
     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
     
    #include <iostream>

    using namespace std;


    char FirstNotRepeatingChar(char *pString)
    {
        if (pString == NULL)
        {
            return '';
        }
        const int tableSize = 256;
        unsigned int hashTable[tableSize];
        for (unsigned int i = 0; i < tableSize; ++i)
        {
            hashTable[i] = 0;
        }

        char *pHashKey = pString;
        while (*(pHashKey) != '')
        {
            hashTable[*pHashKey] ++;
            pHashKey++;
        }

        pHashKey = pString;
        while (*pHashKey != '')
        {
            if (hashTable[*pHashKey] == 1)
            {
                return *pHashKey;
            }
            pHashKey++;
        }
        return '';
    }

    int main()
    {
        cout << FirstNotRepeatingChar("abaccdeff") << endl;
        return 0;
    }
     
  • 相关阅读:
    vue+elementUI,前端导出表格,去除不需要的表格列
    Git撤销远端提交
    剖析 SPI 在 Spring 中的应用
    vivo大规模 Kubernetes 集群自动化运维实践
    如何在Vue项目中,通过点击DOM自动定位VScode中的代码行?
    vivo 容器集群监控系统架构与实践
    nginx rewrite
    nginx location
    IPVS
    得到 spring ApplicationContext
  • 原文地址:https://www.cnblogs.com/codemylife/p/3749305.html
Copyright © 2020-2023  润新知