[經典面試題][字典樹]字串唯一首碼問題,字典首碼
題目
一個檔案裡面有如下字串
cartefdxh
cart
carlkijfwe
chdfwef
cafkekfld
…………
要從檔案中找出唯一能代表該字串的首碼,然後如下輸出
cartefdxh carte
cart cart
carlkijfwe carl
chdfwef ch
cafkekfld caf
以空格分隔…….
思路
用Trie樹實現。為每個節點增加一個變數count,用來記錄一共有幾個字串使用該字元。找節點計數為1的節點或者葉子節點。
代碼
/*--------------------------------------------- * 日期:2015-02-26 * 作者:SJF0115 * 題目: 字串唯一首碼問題 * 來源:經典面試題 * 部落格: -----------------------------------------------*/ #include <iostream> #include <vector> using namespace std; #define MAX 26 struct TrieNode{ // 有幾個字串公用這個字元 int count; TrieNode *next[MAX]; TrieNode(){ count = 0; for(int i = 0;i < MAX;++i){ next[i] = NULL; }//for } }; // 插入 void Insert(TrieNode* &root,string str){ int size = str.size(); if(size == 0){ return; }//if TrieNode *p = root; int val; for(int i = 0;i < size;++i){ val = str[i] - 'a'; if(p->next[val] == NULL){ p->next[val] = new TrieNode(); }//if // 統計共有幾個字串共用該字元 p->next[val]->count++; p = p->next[val]; }//for }//Insert // 字串的唯一首碼表示 string OnlyPrefix(TrieNode* root,string str){ int size = str.size(); TrieNode *p = root; int index = 0,val; for(int i = 0;i < size;++i){ val = str[i] - 'a'; index++; p = p->next[val]; if(p->count == 1){ break; }//if }//for return str.substr(0,index); } // 所有字串的唯一首碼表示 vector<pair<string,string> > AllOnlyPrefix(vector<string> strs){ int size = strs.size(); pair<string,string> prefix; vector<pair<string,string> > vec; if(size <= 0){ return vec; }//if TrieNode *root = new TrieNode(); // 建立字典樹 for(int i = 0;i < size;++i){ Insert(root,strs[i]); }//for // 唯一首碼 for(int i = 0;i < size;++i){ prefix.first = strs[i]; prefix.second = OnlyPrefix(root,strs[i]); vec.push_back(prefix); }//for return vec; } int main() { vector<string> strs = {"book","boom","cartefdxh","cart","carlkijfwe","chdfwef","cafkekfld"}; vector<pair<string,string> > vec = AllOnlyPrefix(strs); for(int i = 0;i < vec.size();++i){ pair<string,string> pair = vec[i]; cout<<pair.first<<" "<<pair.second<<endl; }//for }
引用:
[演算法系列之二十]字典樹(Trie)