在一个字符串中找到第一个只出现一次的字符

问题:在一个字符串中找到只出现一次的字符,如输入abaccdeff,则输出b,假设字符集为ASCII。

思路:ASCII为长度为8的字符集,总共有256种可能。先遍历一遍字符串,将每个字母对应的ASCII值作为字符串计数数组的下标,统计每个字符出现的次数。在遍历一遍字符串将第一个计数为1的字符输出。

#include <iostream>
#include<string.h>

using namespace std;
void firstNotRepeat(const char * str)
{
    const char *s=str;
    if(s==NULL)
        return ;
    int *a=new int[256];
    memset(a,0,256);
    //第一次遍历获得每个字符出现的次数
    while(*s!='\0')
    {
        a[int(*s++)]+=1;
    }
    s=str;
    //第二次遍历输出只出现字符中第一个只出现一次的字符
    while(*s!='\0')
    {
        if(a[int(*s++)]==1)
        {
            cout<< *(--s)<<endl;
            return;
        }
    }
}

int main()
{
    char a[100]="asdfgasdfghjikl";
    firstNotRepeat(a);
    return 0;

}

输出结果:

h

猜你喜欢

转载自blog.csdn.net/u013069552/article/details/80923294