JZ-C-35
劍指offer第三十五題:第一個只出現一次的字符
1 //============================================================================ 2 // Name : JZ-C-35.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description : 第一個只出現一次的字符 7 //============================================================================ 8 9 #include <iostream> 10 #include <stdio.h> 11 #include <string> 12 using namespace std; 13 14 char FirstNotRepeatingChar(char* pString) 15 { 16 if(pString == NULL) 17 return '\0'; 18 19 const int tableSize = 256; 20 unsigned int hashTable[tableSize];//此處定義的哈希表中,key為字符,字符的ASCII碼值為數組下標,value為字符出現次數, 21 for(unsigned int i = 0; i<tableSize; ++ i) 22 hashTable[i] = 0; 23 24 char* pHashKey = pString; 25 while(*(pHashKey) != '\0')//第一次遍歷字符串 26 hashTable[*(pHashKey++)] ++;//使哈希表中對應字符(數組下標為字符ASCII碼值)的出現次數加1 27 28 pHashKey = pString;//再將指針重新指向pString 29 while(*pHashKey != '\0') 30 { 31 if(hashTable[*pHashKey] == 1)//遇到第一個value為1的立即跳出循環,返回 32 return *pHashKey; 33 34 pHashKey++; 35 } 36 37 return '\0'; 38 } 39 40 // ====================測試代碼==================== 41 void Test(char* pString, char expected) 42 { 43 if(FirstNotRepeatingChar(pString) == expected) 44 printf("Test passed.\n"); 45 else 46 printf("Test failed.\n"); 47 } 48 49 int main(int argc, char** argv) 50 { 51 // 常規輸入測試,存在只出現一次的字符 52 Test("google", 'l'); 53 54 // 常規輸入測試,不存在只出現一次的字符 55 Test("aabccdbd", '\0'); 56 57 // 常規輸入測試,所有字符都只出現一次 58 Test("abcdefg", 'a'); 59 60 // 魯棒性測試,輸入NULL 61 Test(NULL, '\0'); 62 63 return 0; 64 }轉載于:https://www.cnblogs.com/Laughing-Lz/p/5604583.html
總結
- 上一篇: 谈色
- 下一篇: beta版本项目冲刺