找出第一个不重复的字母

今天笔试,遇到一个题目要找出一个字符串中第一个不重复的字母,简单写了一下

#include <stdio.h>

void find(const char *str, char *result)
{
	int count[128]={0}, pos[128]={0};
	for (int i=0; str[i]!='\0'; i++)
	{
		int ascii = (int)(str[i]);
		count[ascii]++;
		if (pos[ascii] == 0)
		{
			pos[ascii] = i;
		}
	}
	int min = 99999;
	for (int i=0; i<128; i++)
	{
		if (count[i] == 1 && pos[i]<min)
		{
			*result = (char)i;
			min = pos[i];
		}
	}
}

int main()
{
	char *str = "teeter";
	char result;
	find(str, &result);
	printf("%cn", result);
	return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *