#include <iostream>
#include <string>
#include <map>
using namespace std;
int FirstElement(const string & str)
{
int length = str.size();
if (length <= 0)
{
return -1;
}
else if (length == 1)
{
return 0;
}
else
{
map<char, int> m;
for (int i = 0; i < length; ++i)
{
if (m.find(str[i]) == m.end())
{
m[str[i]] = 1;
}
else
{
m[str[i]]++;
}
}
for (int i = 0; i < length; ++i)
{
if (m[str[i]] == 1)
{
return i;
}
}
return -1;
}
}
int main()
{
string str("a");
cout << str << endl;
int pos = FirstElement(str);
cout << pos << endl;
return 0;
}
【C++代码】字符串中第一个出现一次
最新推荐文章于 2021-06-10 14:41:58 发布