劍指offer統計字符數組中第一次出現的字符

給定一個字符串,例如“abaccdeff”則第一次出現的字符就是b;

#include<iostream>
#include<string>
using namespace std;
void first(const string &input)
{
	if(input.empty())
		return ;
	string::size_type length=input.size();
	int *times=new int[length];
	for(int i=0;i<length;++i)
		times[i]=0;
	string temp;
	int index=0;
	for(int j=0;j<length;++j)
	{
		string::size_type pos=0;
		char  key=input[j];
		pos=temp.find(key);
		if(pos==string::npos)
		{
			temp.push_back(key);
			times[index]++;
			index++;
		}
		else
		{
			times[pos]++;
		}

	}
	for(int i=0;i<temp.size();++i)
	{
		if(times[i]==1)
		{
			cout<<"the first char is"<<temp[i]<<endl;
			return ;
		}
	}
}
int main()
{
	string input("abaccdeff");
	first(input);
	system("pause");
	return 0;
}



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