1. 程式人生 > >案例講解-陣列實現字典樹

案例講解-陣列實現字典樹

看了POJ上的一道題目,大致講的是給出一方語言A詞語所對應的另一方語言B的含義,然後給出B的一些詞語,找到A所對應的翻譯。顯而易見,每個詞語邏輯上可以看成是字典樹,筆者用陣列來實現字典樹,具體程式碼如下,可作參考~吐舌頭

#ifndef  _CRT_SECURE_NO_WARNINGS
#define  _CRT_SECURE_NO_WARNINGS
#endif

#include<stdio.h>
#include<string.h>
#define   MAX_LENTH   10

typedef  struct  DictionTree{
	int   childID[26];      //每個字母后面僅有26中可能,抽象成一種資料結構
	char  data[MAX_LENTH + 1];         //對應的含義
}DictionTree;

DictionTree  Node[200000];  //要分配的足夠多
int          pNodeParent = 0;
int          g_NodeCount = 1;
void init();
void createDictionTree(char*engWod, int engLenth, char*foreign, int foreignLen);
int  search(char*word, int wordLen);


void init()
{
	memset(Node, -1, sizeof(Node));
}

void createDictionTree(char*engWod, int engLenth, char*foreign, int foreignLen)
{
	int tempParent = 0;
	for (int i = 0; i < foreignLen; i++)
	{
		int childIndex = foreign[i] - 'a';
		if (Node[tempParent].childID[childIndex] == -1)//如果說之前沒有使用的話
		{
			Node[tempParent].childID[childIndex] = g_NodeCount;
			tempParent = g_NodeCount;
			g_NodeCount++;
		}
		else
		{
			tempParent = Node[tempParent].childID[childIndex];
		}
	}
	int index;
	for (index = 0; index < engLenth; index++)
	{
		Node[tempParent].data[index] = engWod[index];
	}
	Node[tempParent].data[index] = '\0';
}

int  search(char*word, int wordLen)
{
	int tempParent = 0;
	for (int i = 0; i < wordLen; i++)
	{
		int childIndex = word[i] - 'a';
		if (Node[tempParent].childID[childIndex] == -1)
		{
			return -1;   //表示失敗
		}
		else
		{
			tempParent = Node[tempParent].childID[childIndex];
		}

	}
	return tempParent;
}

int main()
{
	char engWord[MAX_LENTH+1];//前面的單詞
	char foreignMeaning[MAX_LENTH+1]; //後面的含義
	char wordBeLookUp[MAX_LENTH];
	freopen("input.txt", "r", stdin);
	char input[2 * MAX_LENTH + 1];
	init();

	while (true)
	{
		gets(input);
		if (input[0] != '\0')
		{
			int i;
			for (i = 0; input[i] != ' '; i++)
			{
				engWord[i] = input[i];
			}
			engWord[i] = '\0';
			int j;
			int index = 0;
			for (j = i + 1; input[j] != '\0'; j++)
			{
				foreignMeaning[index++] = input[j];
			}
			foreignMeaning[index] = '\0';
			createDictionTree(engWord, i, foreignMeaning, index);
		}
		else
		{
			break;
		}
	}

	while (true)
	{
		if (NULL == gets(wordBeLookUp))
		{
			break;
		}
		if (wordBeLookUp[0] != '\0')
		{
			int result = search(wordBeLookUp, strlen(wordBeLookUp));
			if (result == -1)
			{
				printf("eh\n");
			}
			else
			{
				for (int j = 0; Node[result].data[j] != '\0'; j++)
				{
					printf("%c", Node[result].data[j]);
				}
				printf("\n");
			}
		}
		else
		{
			break;
		}
	}

	return 0;

}

其中輸入input.txt內容如下:

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
aaaaa bbbbb
xxxxx yyyyy
aaaba aaaca
akghd bhaalf


atcay
ittenkay
oopslay
yyyyy