找出字符串中第一次只出现一次的字符(HJ59)

一:解题思路

这道题目和 leetcode387 类似的,可以放在一起进行学习。

二:完整代码示例 (C++版和Java版)

C++:

#include <iostream>
#include <vector>
#include <string>

using namespace std;


void firstUniqueChar(string& s)
{
    if (s.size() == 0) cout << -1 << endl;
    vector<int> count(26, 0);

    for (int i = 0; i < s.size(); i++)
        count[s[i] - 'a']++;

    int j = 0;
    for (; j < s.size(); j++)
    {
        if (count[s[j] - 'a'] == 1)
        {
            cout << s[j] << endl;
            break;
        }
    }

    if (j == s.size()) cout << -1 << endl;
}

int main()
{
    string s = "";

    while (cin >> s)
    {
        firstUniqueChar(s);
    }

    return 0;
}

 

posted @ 2020-08-03 16:54  repinkply  阅读(403)  评论(0)    收藏  举报