According to all the brothers find a word word idea how to deal with

Problem: given a word, if the word b can be obtained by the sequential addition of letters in a word exchange, the definition of b is the brother of a word, for example word abbsd each other brother and dabbs word. Now, given a dictionary, the user enters a word, according to the dictionary to find out how the word brothers What word? It requires time and space efficiency as high as possible.

Solution one:

Hash_map and use the list. 

First define a key, so that the word brothers have the same key, not the brother's words have a different key. For example, the word alphabetically reordered from small to large-after as a key, the key to such bad abd, good is the key dgoo. 

Use the list of words strung together all the brothers, hash_map the key word for the key, value for the starting address list. 

Start by traversing the dictionary, each word will be added to a key in accordance with the list of them. When you need to find the word brothers, only to strike the word key, then hash_map to find the corresponding list can be. 

In this way create hash_map time complexity is O (n), when looking for the word brothers time complexity is O (1).

 

Solution two:

And also using hash_map list.

Each letter corresponds to a prime number, and then let the prime numbers corresponding multiplied by the value obtained hash, the value of this word is the brother of the same, and the number of different words the quality of the product is certainly different phases.

Brothers linked lists all words strung together, hash_map prime number of key words for the multiplication phase, value of the starting address list.

Calculated for the word entered by the user, and then find the hash, the list will get all the brothers traverse the output word.

In this way create hash_map time complexity is O (n), when looking for the word brothers time complexity is O (1).

Guess you like

Origin www.cnblogs.com/wyf-love-dch/p/11535955.html