题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b 

分析:可通过循环每一个字符看后面的子串是否包含这个字符。但是效率不高。一种比较有效的方法是创建一个字符数次hash表。

具体实现如下:

#include <stdio.h>

#include <string.h>

#define N 256

 

int charHash[N] = {0};

 

void initCharHash(const char *s)

{

      while(*s)

      {
            charHash[*s]++;
            s++;

      }

}

char findFirstOnceChar(const char *s)

{

      while(*s)

      {

            if(charHash[*s] == 1)

            {
                  return *s;
            }

            s++;
      }
      return 0;

}

int main(void)

{
      char *str = "abbca";

      initCharHash(str);

      printf("%c\n",findFirstOnceChar(str));

      return 0;

}

觉得这个N太大了,26个即可。

相关文章:

  • 2021-08-28
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-11
  • 2022-12-23
相关资源
相似解决方案