题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路:
利用map。STL模板中的map是一种二叉树的数据存储结构,这种数据结构是采用红黑树来实现的,这棵树具有对数据自动排序的功能。
map存储key-value对,key与value一 一映照。在没有指定比较函数时,元素的插入位置是按key值由小到大插入到红黑树中去的。
例如本题:定义 map<char, int> mp;
对于字符串"abcba",下面这段话是这样的实现的:按key值也就是abcd的大小,从小到大到大地插入到map中,value存储的是key的个数。首先map插入a,key = a, value = 1,然后插入b, key = b, value = 1, 然后插入c, key = c, value = 1, 然后插入b,key = b, value = 2,然后插入a, key = a,value = 2, 然后插入d,key = d, value = 1. c是第一个只出现了一次的字符,c在字符串中的索引为3.
看程序:
for(int i = 0; i < str.size(); ++ i)
mp[str[i]]++;
// 34_FirstNotRepeatChar.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <map>
using namespace std;
class Solution {
public:
int FirstNotRepeatingChar(string str) {
map<char, int> mp;
for(int i = 0; i < str.size(); ++ i)
mp[str[i]]++;
for(int i = 0; i < str.size(); ++ i){
if(mp[str[i]] == 1)
return i;
}
return -1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
string str = "abcbad";
Solution s;
int res = s.FirstNotRepeatingChar(str);
cout<<res<<endl;
}