查找字符串中第一個出現一次的字符

#include <iostream>

using namespace std;

// look up the first character in the string.
// using hash table to reduce the time used.
char look_up(const char* src)
{
	int hash_table[256];// all ascii characters are 256
	const char* p = src;
	memset(hash_table, 0x00, sizeof(hash_table));// sizeof(hash_table) == 4*256
	while(*p != '\0')
	{
		++hash_table[(int)*p];
		++p;
	}

	p = src;
	while(*p != '\0')
	{
		if (hash_table[*p]==1) return *p;
		++p;
	}
	return '\0';
}

int main(int argc, char* argv[])
{
	char* src = "abaccdeff";
	cout<<look_up(src)<<endl;

	return 0;
}
// 使用hashtable,可以以線性時間複雜度

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