建立字典树,在两种情况下无法立即解码:
- 某个字符串插入时,路过其他字符串的终止结点;
- 某个字符串的终止结点是其他字符串的中间结点。
#include<iostream>
using namespace std;
struct trieNode //字典树结点
{
int num; //1表示中间结点,2表示终止结点
trieNode* next[2];
trieNode()
{
num = 0;
for (int i = 0; i < 2; i++)
next[i] = NULL;
}
};
trieNode* root; //根结点
int flag; //能否立即解码
//将字符串s插入字典树
void Insert(char* s)
{
trieNode* p = root;
int k = 0;
while (s[k] != '\0')
{
if (p->next[s[k] - '0'] == NULL)
p->next[s[k] - '0'] = new trieNode;
p = p->next[s[k] - '0'];
if (p->num == 2) //该字符串路过其他字符串的终止结点
{
flag = 1;
break;
}
if (p->num == 1)
{
if (s[k + 1] == '\0') //该字符串的终止结点是其他字符串的中间结点
{
flag = 1;
break;
}
}
p->num = 1;
k++;
}
p->num = 2; //该字符串终止结点
}
//释放字典树
void Free(trieNode* p)
{
for (int i = 0; i < 2; i++)
if (p->next[i])
Free(p->next[i]);
delete p;
}
int main()
{
root = new trieNode;
flag = 0;
char code[10];
int Case = 1;
while (cin >> code)
{
if (code[0] == '9')
{
if (flag)
cout << "Set " << Case++ << " is not immediately decodable" << endl;
else
cout << "Set " << Case++ << " is immediately decodable" << endl;
Free(root);
flag = 0;
root = new trieNode;
}
else
Insert(code);
}
return 0;
}
继续加油。