题目:在字符串中找出第一份只出现一次的字符。如输入"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();
}