17.在一個字符串中找到第一個只出現一次的字符

題目:在一個字符串中找到第一個只出現一次的字符。如輸入abaccdeff,則輸出b。

答案:

//20130113
#include <iostream>
#include <map>
using namespace std;

typedef struct strore
{
	int times;//出現次數
	int count;//出現排序
}strore;
int main()
{
	string s = "abacdebff";
	map<char,strore> mapStore;
	typedef pair<char,strore> makePaire;
	strore st;
	map<char,strore>::iterator it;
	int n = 0;
	for (int i = 0;i < s.size();i++)
	{
		it = mapStore.find(s[i]);
		if (it == mapStore.end())
		{
			
			st.count = n;
			n++;
			st.times = 1;
			mapStore.insert(makePaire(s[i],st));
		}
		else
		{
			it->second.times += 1;
		}
		
	}
	it = mapStore.begin();
	map<char,strore>::iterator mins;
	int minCount = 256;
	for (it++;it != mapStore.end();it++)
	{
		if (it->second.times == 1)
		{
			if (it->second.count < minCount)
			{
				mins = it;
				minCount=it->second.count;
			}
		}
	}
	if (mins->second.times == 1)
	{
		cout<<mins->first<<endl;
	}
	else
	{
		cout<<"no singal char"<<endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章