在一個字符串中找到第一個只出現一次的字符,要求時間複雜度O(n)

// 在一個字符串中找到第一個只出現一次的字符.cpp : Defines the entry point for the console application.
//
//利用hash表,記錄每一個字符出現的次數
//char佔8個位,字符的最大可能數是2^8=256
#include "stdafx.h"
#include <iostream>
using namespace std;
const int TableSize=256;
char FindFirstNoRepeateChar(char *str)
{
	unsigned int hashTable[TableSize];
	for(int i=0;i<TableSize;i++)
		hashTable[i]=0;
	char *strTmp=str;
	while((*strTmp)!='\0')
		hashTable[(*strTmp++)]++;
	strTmp=str;
	while((*strTmp)!='\0')
	{
		if(hashTable[(*strTmp++)]==1)
			return *(--strTmp);
	}
	return *strTmp;
}
int _tmain(int argc, _TCHAR* argv[])
{
	char str[]="ab$d+a+cb$fde";
	cout<<str<<endl;
	cout<<FindFirstNoRepeateChar(str)<<endl;
	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章