程序员面试题精选100题(13)-第一个只出现一次的字符

字号:|
2019-09-22    FW.5VV.CN范文网
程序员面试题精选100题(13)-第一个只出现一次的字符
题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。

分析:这道题是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;
}


测试程序如下:

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
char FirstNotRepeatingChar(char* pString)
{
  if(!pString)
 return 0;
  const int tablesize=256;
  unsigned int hashTable[tablesize];
  for(unsigned int i=0;i<tablesize;i++)
 hashTable[i]=0;
  char* pHashKey=pString;
  while(*pHashKey!='\0')
 hashTable[*(pHashKey++)]++;
   pHashKey=pString;
   while(*pHashKey!='\0')
   {
     if(hashTable[*pHashKey]==1)
return *pHashKey;
pHashKey++;
   }
   return 0;
}


int main(void)
{
  char str[100];
  printf("请输入字符串:");
  gets(str);
  if(FirstNotRepeatingChar(str)==0)
 printf("没有找到!|\n");
  else
 printf("找到了字符串中第一次只出现一次的字符为:%c\n",FirstNotRepeatingChar(str));
  system("pause");
  return 0;
}
————————————————