打印所有可能的有效单词

原文:

给定字典和字符数组,使用数组中的字符打印所有可能的有效单词。

示例:

input : dict - {"go","bat","me","eat","goal", 
                                "boy", "run"} 
        arr[] = {'e','o','b', 'a','m','g', 'l'} 
output : go, me, goal. 

问于:微软采访

其思想是使用 trie 数据结构存储字典,然后使用给定数组的字符在 trie 中搜索单词。

  1. 创建一个空的 trie,并将给定词典中的所有单词插入 trie。
  2. 之后,我们只选择了“arr[]”中的那些字符,它们是特里根的子级。
  3. 为了快速找到一个字符是否存在于数组中,我们创建一个字符数组的散列。

以下是以上想法的实现

c

// c   program to print all valid words that
// are possible using character of array
#include
using namespace std;
// converts key current character into index
// use only 'a' through 'z'
#define char_int(c) ((int)c - (int)'a')
//converts current integer into character
#define int_to_char(c) ((char)c   (char)'a')
// alphabet size
#define size (26)
// trie node
struct trienode
{
    trienode *child[size];
    // isleaf is true if the node represents
    // end of a word
    bool leaf;
};
// returns new trie node (initialized to nulls)
trienode *getnode()
{
    trienode * newnode = new trienode;
    newnode->leaf = false;
    for (int i =0 ; i< size ; i  )
        newnode->child[i] = null;
    return newnode;
}
// if not present, inserts key into trie
// if the key is prefix of trie node, just
// marks leaf node
void insert(trienode *root, char *key)
{
    int n = strlen(key);
    trienode * pchild = root;
    for (int i=0; ichild[index] == null)
            pchild->child[index] = getnode();
        pchild = pchild->child[index];
    }
    // make last node as leaf node
    pchild->leaf = true;
}
// a recursive function to print all possible valid
// words present in array
void searchword(trienode *root, bool hash[], string str)
{
    // if we found word in trie / dictionary
    if (root->leaf == true)
        cout << str << endl ;
    // traverse all child's of current root
    for (int k =0; k < size; k  )
    {
        if (hash[k] == true && root->child[k] != null )
        {
            // add current character
            char c = int_to_char(k);
            // recursively search reaming character of word
            // in trie
            searchword(root->child[k], hash, str   c);
        }
    }
}
// prints all words present in dictionary.
void printallwords(char arr[], trienode *root, int n)
{
    // create a 'has' array that will store all present
    // character in arr[]
    bool hash[size];
    for (int i = 0 ; i < n; i  )
        hash[char_int(arr[i])] = true;
    // tempary node
    trienode *pchild = root ;
    // string to hold output words
    string str = "";
    // traverse all matrix elements. there are only 26
    // character possible in char array
    for (int i = 0 ; i < size ; i  )
    {
        // we start searching for word in dictionary
        // if we found a character which is child
        // of trie root
        if (hash[i] == true && pchild->child[i] )
        {
            str = str (char)int_to_char(i);
            searchword(pchild->child[i], hash, str);
            str = "";
        }
    }
}
//driver program to test above function
int main()
{
    // let the given dictionary be following
    char dict[][20] = {"go", "bat", "me", "eat",
                       "goal", "boy", "run"} ;
    // root node of trie
    trienode *root = getnode();
    // insert all words of dictionary into trie
    int n = sizeof(dict)/sizeof(dict[0]);
    for (int i=0; i

java 语言(一种计算机语言,尤用于创建网站)

// java program to print all valid words that
// are possible using character of array
public class searchdict_chararray {
    // alphabet size
    static final int size = 26;
    // trie node
    static class trienode
    {
        trienode[] child = new trienode[size];
        // isleaf is true if the node represents
        // end of a word
        boolean leaf;
        // constructor
        public trienode() {
            leaf = false;
            for (int i =0 ; i< size ; i  )
                    child[i] = null;
        }
    }
    // if not present, inserts key into trie
    // if the key is prefix of trie node, just
    // marks leaf node
    static void insert(trienode root, string key)
    {
        int n = key.length();
        trienode pchild = root;
        for (int i=0; i

c

// c# program to print all valid words that 
// are possible using character of array 
using system; 
public class searchdict_chararray 
{ 
    // alphabet size 
    static readonly int size = 26; 
    // trie node 
    public class trienode 
    { 
        public trienode[] child = new trienode[size]; 
        // isleaf is true if the node represents 
        // end of a word 
        public boolean leaf; 
        // constructor 
        public trienode() 
        { 
            leaf = false; 
            for (int i =0 ; i< size ; i  ) 
                    child[i] = null; 
        } 
    } 
    // if not present, inserts key into trie 
    // if the key is prefix of trie node, just 
    // marks leaf node 
    static void insert(trienode root, string key) 
    { 
        int n = key.length; 
        trienode pchild = root; 
        for (int i = 0; i < n; i  ) 
        { 
            int index = key[i] - 'a'; 
            if (pchild.child[index] == null) 
                pchild.child[index] = new trienode(); 
            pchild = pchild.child[index]; 
        } 
        // make last node as leaf node 
        pchild.leaf = true; 
    } 
    // a recursive function to print all possible valid 
    // words present in array 
    static void searchword(trienode root, boolean []hash, 
                                            string str) 
    { 
        // if we found word in trie / dictionary 
        if (root.leaf == true) 
            console.writeline(str); 
        // traverse all child's of current root 
        for (int k = 0; k < size; k  ) 
        { 
            if (hash[k] == true && root.child[k] != null ) 
            { 
                // add current character 
                char c = (char) (k   'a'); 
                // recursively search reaming character 
                // of word in trie 
                searchword(root.child[k], hash, str   c); 
            } 
        } 
    } 
    // prints all words present in dictionary. 
    static void printallwords(char []arr, trienode root, 
                                            int n) 
    { 
        // create a 'has' array that will store all 
        // present character in arr[] 
        boolean[] hash = new boolean[size]; 
        for (int i = 0 ; i < n; i  ) 
            hash[arr[i] - 'a'] = true; 
        // tempary node 
        trienode pchild = root ; 
        // string to hold output words 
        string str = ""; 
        // traverse all matrix elements. there are only 
        // 26 character possible in char array 
        for (int i = 0 ; i < size ; i  ) 
        { 
            // we start searching for word in dictionary 
            // if we found a character which is child 
            // of trie root 
            if (hash[i] == true && pchild.child[i] != null ) 
            { 
                str = str (char)(i   'a'); 
                searchword(pchild.child[i], hash, str); 
                str = ""; 
            } 
        } 
    } 
    // driver code 
    public static void main(string []args) 
    { 
        // let the given dictionary be following 
        string []dict = {"go", "bat", "me", "eat", 
                        "goal", "boy", "run"} ; 
        // root node of trie 
        trienode root = new trienode(); 
        // insert all words of dictionary into trie 
        int n = dict.length; 
        for (int i = 0; i < n; i  ) 
            insert(root, dict[i]); 
        char []arr = {'e', 'o', 'b', 'a', 'm', 'g', 'l'} ; 
        int n = arr.length; 
        printallwords(arr, root, n); 
    } 
} 
/* this code is contributed by princiraj1992 */

output:

go
goal
me

本文由 供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 contribute@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。

如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。