给定一个字符串,找到第一个只出现一次的字符的下标,找不到输出-1。

1. 给定一个字符串,找到第一个只出现一次的字符的下标,找不到输出-1。

sample:

输入:“abcdefcba”

输出:3

解法:先遍历字符串,用一个map记录每个字符出现的次数,再次遍历字符串,找到第一个只出现一次的字符,复杂度为O(n)。

 

#include <iostream>
#include <string>
#include <cstring>
#include <map>
using namespace std;

int getCharIndex(const char *str)
{
map<char, int> cmap;
int length = strlen(str);
for (int i = 0; i < length; ++i)
++ cmap[str[i]];

int ret = -1;
for (int i = 0; i < length; ++i)
if (cmap[str[i]] == 1)
{
ret = i;
break;
}

return ret;
}

int main()
{
string str;
cin >> str;
cout << getCharIndex(str.c_str()) << endl;
}

posted @ 2017-06-25 07:39  code666  阅读(1593)  评论(0编辑  收藏  举报