Split string into words

后端 未结 4 1111
予麋鹿
予麋鹿 2021-02-03 13:27

I am looking for the most efficient algorithm to form all possible combinations of words from a string. For example:

Input String: forevercarrot

Output:

foreve         


        
4条回答
  •  深忆病人
    2021-02-03 14:25

    Use a prefix tree for your list of known words. Probably libs like myspell already do so. Try using a ready-made one.

    Once you found a match (e.g. 'car'), split your computation: one branch starts to look for a new word ('rot'), another continues to explore variants of current beginning ('carrot').

    Effectively you maintain a queue of pairs (start_position, current_position) of offsets into your string every time you split the computation. Several threads can pop from this queue in parallel and try to continue a word that starts from start_position and is already known up to current_position of the pair, but does not end there. When a word is found, it is reported and another pair is popped from the queue. When it's impossible, no result is generated. When a split occurs, a new pair is added to the end of the queue. Initially the queue contains a (0,0).

提交回复
热议问题