H面试程序(12): 输出字符串中第一个只出现一次的字母

题目描述:

              若字符串str为'' sbdddsbfc'',则输出 f;

              若字符串str为''aabbccdd'',则输出:字符串str中的字符都出现两次以上

 

#include <stdio.h>
#include<malloc.h>
#include<memory.h>
#include<assert.h>

int  find_first_char(char*  str)  
{  
   assert(str);
   char * phash = (char *)malloc(256*sizeof(char)); //进行一些初始化的工作


   //此处也可以申请栈的空间,申请字符数组char[256] = {0};作为哈希数组
   assert(phash);
   memset(phash, 0, 256);   //把申请的空间都设为0


   int i = 0;
   while(str[i] != '\0')    //将str1在phash数组中映射一遍,对应的字符每出现一次就加1
   {
	   phash[str[i]] += 1;   
       i++;
   }


    i =  0;
	while(str[i] != '\0')  //第二次扫描,按字符串的顺序,找到第一个在字符串出现一次的字符
    {
		if(phash[str[i]] == 1)
		   return i ;
		i++;
	}

	if(str[i] = '\0')  //整个字符扫描结束后,都没发现,返回0,代表字符串中的所有字符都出现两次以上
		   return 0;
		 
	
}
int main()
{
	char str[] ="aabbdcc";   
	

	int a = find_first_char(str); //a为字符串中第一个出现一次的字母在数组中的位置,0代表没有这样的字符
	if(0 ==a)  
		printf("字符串str中的字符都出现一次以上!!!\n");
	else
	    printf("%c\n",str[a]); 
	
	return 0;

}  


 

 

posted @ 2013-08-20 20:16  pangbangb  阅读(249)  评论(0)    收藏  举报