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

#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    string str;
    getline(cin, str);
    vector<char> strline ;
    vector<int> cnt;
    int len = str.length();
    // int dis;
    for (int i = 0 ; i < len ; i++) {
        char ch = str[i];
        auto it = std::find(strline.begin(), strline.end(), ch);
        int dis = std::distance(strline.begin(),
                            it);//找到的指定元素在vector中的位置
        if (dis ==
                strline.size()) { //在当前vector中没找到目标元素,把当前元素放入,并且对应计数器置1
            strline.push_back(ch);
            cnt.push_back(1);
        } else { //在当前vector找到,在对应计数器加1
            cnt[dis]++;
        }
    }

    for (int i = 0 ; i < cnt.size() ; i++) {//第一个计数器为1时,输出计数器位置对应的字符
        if (cnt[i] == 1) {
            cout << strline[i];
            break;
        }
    }
    auto it = std::find(cnt.begin(), cnt.end(), 1);
    int dis = std::distance(cnt.begin(), it);
    if (dis == cnt.size()) {//没找到只出现一次的字符
        cout << -1;
    }


}

全部评论

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务