第一个只出现一次的字符

来自:剑指offer


分析:通过两次遍历字符串计算得到,第一次遍历字符串通过一个数组确定每个字符出现的次数,第二次遍历字符串确定第一个只出现一次字符是谁。时间复杂度为O(n)。

#include "stdafx.h"
#include <iostream>
using namespace std;

char FirstNotRepeatingChar(const char* pString)
{
	if ( pString == NULL )
		return '\0';

	unsigned int hashTable[256];
	memset(hashTable, 0, sizeof(unsigned int)*256);

	const char* pStart = pString;
	while ( *pStart != '\0' )
		hashTable[*(pStart++)]++;

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

int _tmain(int argc, _TCHAR* argv[])
{
	char* p = "abaccdefdef";
	cout << FirstNotRepeatingChar(p) <<endl;

	system("pause");
	return 0;
}

扩展:

1:实现一函数,给定两个字符串str1和str2,将字符串str2中在str1出现的字符删除掉。例如,str1=“We are strudent”,str2=“eas”,最终返回“W r tudnt”。

做法:遍历str2并将其字符放入哈希数组中,再遍历str1,去掉哈希数组中存在的字符即可。与上题思路一致。时间复杂度为O(n+m),n和m分别为str1和str2的长度。空间为O(1)。

2:实现一函数,将字符串中出现重复字符全部去掉。例如,str=“google”,那么返回为“gole”。

做法:类似,可用一个布尔数组去记录。第一次出现标志位true,当第二次访问该字符时,当前标志位为true时,删除当前字符。时间复杂度为O(n),n为str的长度。空间为O(1)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值