题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
思路:我的想法和原文作者的基本是一样的,就是用hash表来统计字符串中每个字符出现的次数。我和他的做法不一样的地方在于,原文作者是通过第二次遍历字符串来得到第一个只出现一次的字符,而我的想法是,维护一个链表,最后通过遍历这个链表得到满足条件的字符。两种方法其实差不多。
我的代码:
- #define HASH_LEN 256
- struct node{
- char ch;
- int count;
- struct node *next;
- };
- /*
- * 返回 -2:出错
- * 返回 -1:没有符合条件的字符
- * 返回 0:成功返回
- */
- int foo13(char *str, char *ret){
- struct node hash[HASH_LEN];
- int i;
- char *cur = str;
- struct node *head;
- struct node *tail;
- struct node *p;
- if(!cur)
- return -2;
- if(*cur=='/0'){
- *ret = '/0';
- return 0;
- }
- memset(hash,0,HASH_LEN*sizeof(struct node));
- head = tail = (struct node*)malloc(sizeof(struct node));
- head->ch = head->count = 0;
- head->next = NULL;
- while('/0'!=*cur){
- if(0==hash[*cur].count){ //第一次出现
- hash[*cur].ch = *cur;
- hash[*cur].count++;
- tail->next = &hash[*cur];
- tail = &hash[*cur];
- }else
- hash[*cur].count++;
- printf("[debug]%c第%d次出现/n",*cur,hash[*cur].count);
- cur++;
- }
- if(head->next){
- p = head->next;
- while(p){
- if(p->count==1){
- *ret = p->ch;
- return 0;
- }else
- p = p->next;
- }
- }
- return -1;
- }
对于这个链表,其实可以进行改动。比如,每当更新字符出现次数的时候,也更新这个链表,使链表成为一个按照字符出现次数升序排列的队列。有这样一个链表,就可以找出诸如字符串中出现次数最多的字符等等之类问题的答案。
最后,引用下原文。
============ 以下内容引自原文 ==================
分析:这道题是2006年google的一道笔试题。
看到这道题时,最直观的想法是从头开始扫描这个字符串中的每个字符。当访问到某字符时拿这个字符和后面的每个字符相比较,如果在后面没有发现重复的字符,则该字符就是只出现一次的字符。如果字符串有n个字符,每个字符可能与后面的O(n)个字符相比较,因此这种思路时间复杂度是O(n2)。我们试着去找一个更快的方法。
由于题目与字符出现的次数相关,我们是不是可以统计每个字符在该字符串中出现的次数?要达到这个目的,我们需要一个数据容器来存放每个字符的出现次数。在这个数据容器中可以根据字符来查找它出现的次数,也就是说这个容器的作用是把一个字符映射成一个数字。在常用的数据容器中,哈希表正是这个用途。
哈希表是一种比较复杂的数据结构。由于比较复杂,STL中没有实现哈希表,因此需要我们自己实现一个。但由于本题的特殊性,我们只需要一个非常简单的哈希表就能满足要求。由于字符(char)是一个长度为8的数据类型,因此总共有可能256 种可能。于是我们创建一个长度为256的数组,每个字母根据其ASCII码值作为数组的下标对应数组的对应项,而数组中存储的是每个字符对应的次数。这样我们就创建了一个大小为256,以字符ASCII码为键值的哈希表。
我们第一遍扫描这个数组时,每碰到一个字符,在哈希表中找到对应的项并把出现的次数增加一次。这样在进行第二次扫描时,就能直接从哈希表中得到每个字符出现的次数了。
参考代码如下:
///
// Find the first char which appears only once in a string
// Input: pString - the string
// Output: the first not repeating char if the string has, otherwise 0
///
char FirstNotRepeatingChar(char* pString)
{
// invalid input
if(!pString)
return 0;
// get a hash table, and initialize it
const int tableSize = 256;
unsigned int hashTable[tableSize];
for(unsigned int i = 0; i < tableSize; ++ i)
hashTable[i] = 0;
// get the how many times each char appears in the string
char* pHashKey = pString;
while(*(pHashKey) != '/0')
hashTable[*(pHashKey++)] ++;
// find the first char which appears only once in a string
pHashKey = pString;
while(*pHashKey != '/0')
{
if(hashTable[*pHashKey] == 1)
return *pHashKey;
pHashKey++;
}
// if the string is empty
// or every char in the string appears at least twice
return 0;
}
原文地址:http://blog.csdn.net/xianliti/article/details/5691984