第一个只出现一次的字符 用hashMap和hashTable实现

题目:在字符串中找出第一份只出现一次的字符。如输入"abbacdgdfgfcv",输出‘v’


剑指Offer是用以空间换时间的HashTable的方法 和利用HashMap的key-value对应方法。

下面程序已经过编译:

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

void findIndex(){
	string s="abbacdgdfgfcv";
	if(s.size()==0)
	{
		return;
	}
	else if(s.size()==1)
	{
		cout<<s[0]<<endl;
	}
	else{
		map<char,int> mapFind;
		bool check=false;
		int j=0;
		for(int i=0;i<s.size();i++)
		{
			if(mapFind[s[i]]==NULL)
			{
				mapFind[s[i]]=1;
			}
			else
				mapFind[s[i]]++;
		}
		for(j=0;j<s.size();j++)
		{
			if(mapFind[s[j]]==1)
			{
				check=true;
				//cout<<s[j]<<endl;
				break;
			}
		}
		if(check)
			cout<<s[j]<<endl;
		else
			cout<<"NO that number!"<<endl;
	}
}
char findChar(char* pstring)
{
	if(pstring==NULL||*pstring==NULL)
	{
		return '\0';
	}
	const int tableSize = 256;
	unsigned int hashTable[tableSize];
	memset(hashTable,0,tableSize*sizeof(int));
	char * p = pstring;
	while(*p!='\0')
	{
		hashTable[*p]++;
		p++;
	}
	p=pstring;
	while(*p!='\0')
	{
		if(hashTable[*p]==1)
			return *p;
		p++;
	}
	return '\0';
}
void main(){
	/*char ss[] ="abbacdgdfgfc";
	char *s=ss;
	char res=findChar(s);
	cout<<res<<endl;*/
	findIndex();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值