Word Jumble Algorithm

后端 未结 5 1307
执笔经年
执笔经年 2021-01-18 02:04

Given a word jumble (i.e. ofbaor), what would be an approach to unscramble the letters to create a real word (i.e. foobar)? I could see this having a couple of approaches, a

5条回答
  •  走了就别回头了
    2021-01-18 02:25

    Depending on the length of the string WhirlWind's approach could be faster, but an alternative way of doing it which has more or less O(n) complexity is instead of creating all the permutations of the string and looking them up, you go through all the words in the dictionary and see if each can be built from the input string.

    A really smart algorithm that knows the number of words in the dictionary in advance could do something like this:

    sort letters in jumbled string
    if factorial(length of jumbled string) > count of words in dictionary:
        for each word in dictionary:
           sort letters in dictionary word 
           if sorted letters in dictionary word == sorted letters in jumbled string:
               append original dictionary word to acceptable word list
    else:
        create permutation list of jumbled letters
        for each permutation of letters:
            search in dictionary for permutation
            if permutation in dictionary:
                add word to acceptable word list
    

提交回复
热议问题