zoukankan      html  css  js  c++  java
  • 【面试题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;
    }
     
  • 相关阅读:
    左孩子右兄弟的字典树
    UVA 1401 Remember the Word
    HDOJ 4770 Lights Against Dudely
    UvaLA 3938 "Ray, Pass me the dishes!"
    UVA
    Codeforces 215A A.Sereja and Coat Rack
    Codeforces 215B B.Sereja and Suffixes
    HDU 4788 Hard Disk Drive
    HDU 2095 find your present (2)
    图的连通性问题—学习笔记
  • 原文地址:https://www.cnblogs.com/codemylife/p/3749305.html
Copyright © 2011-2022 走看看