[Huawei] machine test 108 questions to find out the first string of characters appears only once

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011544909/article/details/79944659

Input Description:
enter a non-empty string

Description Output:
output of the first character appears only once, if there is no output -1

Example 1
Input
asdfasdfo
output
o


We can use the find function and rfind stl function library (reverse lookup function), if the forward lookup and reverse lookup returned values ​​are equal, it is possible to determine the character appears only once, as follows:


#include  <bits/stdc++.h>
using namespace std;
int flag[128];

int main()
{
    string str;
    while(cin>>str)
    {
        int i;
        for(i=0;i<str.size();i++)
        {
            if(str.find(str[i])==str.rfind(str[i]))
            {
                cout<<str[i]<<endl;
                break;
            }
        }
        if(i==str.size())
            cout<<-1<<endl;
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/u011544909/article/details/79944659