剑指offer------数组------第一个只出现一次的字符

题目

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。

思路

建立一个哈希表,第一次扫描的时候,统计每个字符的出现次数。第二次扫描的时候,如果该字符出现的次数为1,则返回这个字符的位置。

代码:

class Solution
{
public:
	int FirstNotRepeatingchar(string str)
	{
		int length=str.size();
		if(length==0)
			return -1;
		
		//字典
		map<char,int>item;
		for(int i=0;i<length;i++)
		{
			item[str[i]]++;
		}
		for(int i=0;i<length;i++)
		{
			if(item[str[i]]==1)
				return i;
		}
		return -1;
	}
};
char FirstNotRepeatingchar(char* pString)
{
	if(pString==NULL)
		return '\0';
	
	const int tableSize=256;
	unsigned int hashTable[tableSize];
	
	for(unsigned int i=0;i<tableSize;i++)
		hashTable[i]=0;
	
	char* pHashKey=pString;
	while(*(pHashKey)!='\0')
		hashTable[*(pHashKey++)]++;
		
	pHashKey=pString;
	
	while(*pHashKey!='\0')
	{
		if(hashTable[*pHashKey]==1)
			return *pHashKey;
			
		pHashKey++;
	}
	return '\0';
}

猜你喜欢

转载自blog.csdn.net/qq_39503189/article/details/82658489
今日推荐