The first character that appears only once (OJ question)

Insert image description here

The main idea of ​​this question:

Create a new tmp array, use the tmp array to store the number of times each character appears;
judge whether it appears for the first time by accumulating count;
finally, judge whether the character appears for the first time by traversing the array tmp;

int FirstNotRepeatingChar(char* str ) {
    
    
    int len = strlen(str);//计算字符数组长度
    int i,j,count=0;
    int tmp[10000]={
    
    0};//创建一个新数组,用来存存储每个字符出现过的次数;
    for (i=0;i<len;i++)
    {
    
    
        count=0;
        for (j=0;j<len;j++)
        {
    
    
            if (str[i]==str[j])//如果碰到相同的字符,count就++
            {
    
    
                count++;
            }
        }
        tmp[i]=count;//把一趟遍历后这个字符的出现次数存储到tmp数组中       
    }
    for (i=0;i<len;i++)
    {
    
    
        if (tmp[i]==1)//通过遍历数组tmp判断字符是否第一次出现;
        return i;//返回第一次出现的下标
    }
    return -1;
}

Guess you like

Origin blog.csdn.net/originalHSL/article/details/131577444