[Classic Interview Questions] [dictionary tree] unique string prefix
Question
A file contains the following strings:
Cartefdxh
Cart
Carlkijfwe
Chdfwef
Cafkek.pdf
............
Find the unique prefix that represents the string from the file, and then output the following
Cartefdxh carte
Cart
Carlkijfwe carl
Chdfwef ch
Cafkekw.caf
Separated by spaces .......
Ideas
Use the Trie tree. Add a variable count for each node to record several strings that use this character. Find the node or leaf node with a node count of 1.
Code
/* ------------------------------------------- * Date: 2015-02-26 * Author: SJF0115 * question: String unique prefix * Source: Classic interview questions * blog: Author */# include
# Include
Using namespace std; # define MAX 26 struct TrieNode {// several strings share this character int count; TrieNode * next [MAX]; TrieNode () {count = 0; for (int I = 0; I <MAX; ++ I) {next [I] = NULL;} // }}; // Insert 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 // statistics a total of several strings share this character p-> next [val]-> count ++; p = p-> next [val];} // for} // the unique prefix of the Insert // string indicates 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);} // the unique prefix of all strings to indicate the vector
> AllOnlyPrefix (vector
Strs) {int size = strs. size (); pair
Prefix; vector
> Vec; if (size <= 0) {return vec;} // if TrieNode * root = new TrieNode (); // create a dictionary tree for (int I = 0; I <size; ++ I) {Insert (root, strs [I]);} // for // unique prefix 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
Strs = {"book", "boom", "cartefdxh", "cart", "carlkijfwe", "chdfwef", "cafkekfld"}; vector
> Vec = AllOnlyPrefix (strs); for (int I = 0; I <vec. size (); ++ I) {pair
Pair = vec [I]; cout <
Reference:
[20 of algorithm series] dictionary tree (Trie)