要求第一个只出现一次的字符,那么就跟字符出现的次数有关。我们考虑如何统计字符出现的次数,然后找出第一个次数为1的那个字符。如果从先往后遍历一个一个的比对,效率自然太低。这里我们需要一个数据容器来保存字符出现次数,并且能够通过字符找出其相对应的次数。哈希表就是一种常用用的容器。
我们可以定义哈希表的键值(Key)是字符的ASCII值,而值(Value)是该字符出现的次数。同时我们需要扫描两次字符串,第一次扫描字符串时,每扫描到一个字符就在哈希表的对应项中把次数加1。接下来第二次扫描的时候,没扫描到一个字符就能在哈希表中得到该字符出现的次数。找出第一个Value为1的那个key就是我们需要找到那个字符。
// FirstNotRepeatingChar.cpp : 定义控制台应用程序的入口点。
求字符串中第一个出现一次的字符
//可以定义哈希表的键值(Key)是字符的ASCII值,而值(Value)是该字符出现的次数
#include "stdafx.h"
#include <stdlib.h>//for system()
#include <stdio.h>
#include <string.h>//for strlen()
char FirstNotRepeatingchar(char* pStr)
{
if(pStr == NULL)
return '\0';
int len = strlen(pStr);
int *hashTable = new int[len];
int i = 0;
for(;i < len;i++)
hashTable[i] = 0;
//第一循环遍历求出字符出现的次数
char* index = pStr;
while(*index != '\0')
hashTable[(*(index++))%len]++;
index = pStr;
//第二次循环遍历,求出第一个出现一次的字符,每次都是按照字符串的顺序遍历
while (*index != '\0')
{
if(hashTable[(*(index))%len] == 1)
return *index;
index++;
}
return '\0';
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str = "aansldfnslfdzlkhjsdah";
char out = FirstNotRepeatingchar(str);
if(out)
printf("字符串中第一个出现一次的字符是:%c\n",out);
system("pause");
return 0;
}