在 C++ 中查找给定列表中每个单词的最短唯一前缀
在此问题中,我们给定一个单词数组 arr[]。我们的任务是找到给定列表中每个单词的最短唯一前缀。
我们举个例子来理解这个问题,
输入
arr[] = {“learn”, “programming”, “code”}输出
c leap lear p
解决方案方法
解决此问题的简单方法是找到单词的所有前缀。然后检查它是否是数组中任何其他单词的前缀。如果不是,则打印出来。
一种有效的方法是使用词典树数据结构。我们将构建一个词典树并存储所有单词。然后,在插入时查找访问每个单词的频率。使用单词,我们将找到它到根的路径,即前缀。我们将从频率为 1 的节点开始打印所有前缀。
程序来说明我们解决方案的工作原理,
示例
#include<iostream>
using namespace std;
#define MAX 256
struct trieNode {
struct trieNode *child[MAX];
int freq;
};
struct trieNode *newTrieNode(void){
struct trieNode *newNode = new trieNode;
newNode->freq = 1;
for (int i = 0; i<MAX; i++)
newNode->child[i] = NULL;
return newNode;
}
void insert(struct trieNode *root, string str) {
int len = str.length();
struct trieNode *pCrawl = root;
for (int level = 0; level<len; level++) {
int index = str[level];
if (!pCrawl->child[index])
pCrawl->child[index] = newTrieNode();
else
(pCrawl->child[index]->freq)++;
pCrawl = pCrawl->child[index];
}
}
void findShortestUniquePrefixRec(struct trieNode *root, char prefixChar[], int ind) {
if (root == NULL)
return;
if (root->freq == 1) {
prefixChar[ind] = '\0';
cout<<prefixChar<<endl;
return;
}
for (int i=0; i<MAX; i++) {
if (root->child[i] != NULL) {
prefixChar[ind] = i;
findShortestUniquePrefixRec(root->child[i], prefixChar, ind+1);
}
}
}
void findShortestUniquePrefix(string arr[], int n) {
struct trieNode *root = newTrieNode();
root->freq = 0;
for (int i = 0; i<n; i++)
insert(root, arr[i]);
char prefixChar[250];
findShortestUniquePrefixRec(root, prefixChar, 0);
}
int main() {
string arr[] = {"learn", "programming", "code", "leap"};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"All Shortest unique prefix for every words in a given list are : \n";
findShortestUniquePrefix(arr, n);
return 0;
}输出
All Shortest unique prefix for every words in a given list are − c leap lear p
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP