题解 | #找出字符串中第一个只出现一次的字符#

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

https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

// 1. 得到字符串
// 2. 借助字符表快慢指针去重
// 3. 遍历去重后的字符串,找到第一个次数为1的字符并输出

int main() {
    
    char input[1010] = {0};
    gets(input);

    int alpha[26] = {0};
    int fast = 0;
    int slow = 0;
    int len = strlen(input);

    for(; fast < len; ++ fast)
    {
        ++ alpha[input[fast] - 'a'];
        if(alpha[input[fast]-'a'] == 1)
        {
            //第一次出现则保留
            input[slow] = input[fast];
            ++ slow;
        }
        //出现次数大于1则将此字符废弃掉

    }

    for(int i = 0; i < slow; ++ i)
    {
        if(alpha[input[i]-'a'] == 1)
        {
            putchar(input[i]);
            return 0;
        }
    }

    printf("%d", -1);

    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务