剑指Offer----面试题35:第一个只出现一次的字符

本文介绍三种方法来找出字符串中首次出现的非重复字符,包括逐一比较、哈希表和哈希数组的方法,并提供了C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:


在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出'b';

方法一:


方法分析:从头开始扫描字符,如果从头到尾(除了自己以外)没有遇到相同的字符,则返回自己,否则,进行下一个字符的扫描,如果没有只出现一次的字符或者输入的字符串为空则返回' ';

源代码如下:
/*
	在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出'b';
*/

#include<iostream>
#include<vector>
#include<string>

using namespace std;

char Function(string str)
{
	if (str.empty())
		return ' ';

	int len = str.length();
	bool flag = false;

	for (int i = 0; i < len; ++i)//从前往后,将该位置的元素依次同其他文职上的元素作比较
	{
		flag = false;
		for (int j = 0; j < len; ++j)
		{
			if (i == j)//如果位置相同,则直接略过
			{
				continue;
			}

			if (str[i] == str[j])//如果该元素有重复则将flag置为true;
			{
				flag = true;
				break;
			}				
		}
		if (!flag)
			return str[i];
	}

	return ' ';//将前边n-1个元素都有重复,则返回最后一个元素的值
}

int main()
{
	string str = "abaccdeff";
	cout << Function(str) << endl;
	string str2 = "aabbccddeef";
	cout << Function(str2) << endl;
	string str3;
	cout << Function(str3) << endl;
	string str4 = "aabbccdd";
	cout << Function(str4) << endl;

	system("pause");
	return 0;
}

运行结果:
b
f


请按任意键继续. . .

方法二:


利用hash_table(不是C++11中标准的函数);

源代码如下:
#include<iostream>
#include<hash_map>
#include<string>

using namespace std;

char Function2(string str)
{
	if (str.empty())
		return ' ';

	int len = str.length();
	hash_map<char, int> mhashMap;

	for (int i = 0; i < len; ++i)
		mhashMap[str[i]]++;

	for (const auto &t : mhashMap)
	{
		if (t.second == 1)
			return t.first;
	}

	return ' ';
}

int main()
{
	string str = "abaccdeff";
	cout << Function2(str) << endl;
	string str2 = "aabbccddeef";
	cout << Function2(str2) << endl;
	string str3;
	cout << Function2(str3) << endl;
	string str4 = "aabbccdd";
	cout << Function2(str4) << endl;

	system("pause");
	return 0;
}

运行结果:
b
f


请按任意键继续. . .

方法三:



源代码如下:
#include<iostream>

using namespace std;

char FirstNotRepeatingChar(char *str)
{
	if (str == nullptr)
		return ' ';

	const int tableSize = 256;
	unsigned int hashTable[tableSize] = { 0 };

	char *pHashKey = str;
	while (*(pHashKey) != '\0')
		hashTable[*(pHashKey++)]++;

	pHashKey = str;
	while (*pHashKey != '\0')
	{
		if (hashTable[*pHashKey] == 1)
			return *pHashKey;
		else
			pHashKey++;
	}

	return '\0';
}

int main()
{
	char str[] = "abaccdeff";
	cout << FirstNotRepeatingChar(str) << endl;
	char str2[] = "aabbccddeef";
	cout << FirstNotRepeatingChar(str2) << endl;
	char str3[] = "";
	cout << FirstNotRepeatingChar(str3) << endl;
	char str4[] = "aabbccdd";
	cout << FirstNotRepeatingChar(str4) << endl;

	system("pause");
	return 0;
}

运行结果如下:
b
f



请按任意键继续. . .






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值