剑指offer 35(186页)

    xiaoxiao2022-06-24  43

    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的话有现成的哈希表可以直接用,

    转载请注明原文地址: https://ju.6miu.com/read-1123837.html

    最新回复(0)