【编程之法】第一章习题 7.第一个只出现一次的字符

来源:互联网 发布:3d游戏编程大师技巧 编辑:程序博客网 时间:2024/05/18 03:15

在一个字符串中找到第一个只出现一次的字符。例如,输入”abaccdeff”,则输出b。


解题思路

  • 第一次遍历:用数组存储每个字符出现次数
  • 第二次遍历:字符串第一个出现次数为1次的即为所求。
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int maxn = 1000;int num[maxn] = {0};         // 记录每个字符出现次数int main(){    memset(num, 0, sizeof(num));    // cstring 下面的用于初始化的函数    string str;    cin >> str;    // 遍历,统计每一个字符出现的次数    for(int i = 0; i < str.length(); ++i)    {        num[str[i]]++;    }    int result = -1;    // 存储结果    for(int i = 0; i < str.length(); ++i)    {        // 按字符串遍历,第一个出现一次的字符即第一个只出现一次的字符        if(num[str[i]] == 1)        {            result = i;            break;        }    }    // 输出    if(result == -1)    {        cout << "ERROR";    }    else    {        cout << str[result];    }    return 0;}

运行结果
这里写图片描述

2 0
原创粉丝点击