剑指offer 35(186页)

来源:互联网 发布:编程谜题 百度云 编辑:程序博客网 时间:2024/06/06 13:13

Q:找到输入字符串中第一个只出现一次的字符。
A:利用数组构成一个简单的哈希表,这种解决方案还可以解决出现两次,出现三次。。

#include <iostream>using namespace std;char FirstNotRepeatingChar(const char *pString){    if (pString == NULL)        return '\0';    const int tableSize = 256;    unsigned int hashTable[tableSize];    for (int i = 0;i<tableSize;i++)        hashTable[i] = 0;    const char *pNew = pString;    while(*pNew != '\0')    {        hashTable[*pNew]++;        pNew++;    }    pNew = pString;    while(*pNew != '\0')    {        if (hashTable[*pNew] == 1)            return *pNew;        pNew++;    }    return '\0';}void Test(char *pString, char expected){    if (FirstNotRepeatingChar(pString) == expected)        cout << "Test passed" << endl;    else        cout << "Test failed" << endl;}int main(){    Test("google",'l');    Test("aabbccdbd",'\0');    Test("abcdefg",'a');    Test(NULL,'\0');    return 0;}

引申:如果是出现中文怎么办?
如果是unicode编码空间消耗太大,c++暂时未想到好的解决方案。
不过java的话有现成的哈希表可以直接用,

0 0
原创粉丝点击