我需要将字符串拆分为单词,以便每个单词都来自字典。还要确保选择左边最长的单词。因此
thisisinsane => this is insane (correct as longest possible word from left)
thisisinsane => this is in sane(wrong)
Assuming 'this', 'is', 'in', 'insane' are all words in the dictionary.
我设法通过从字符串的末尾遍历到开头匹配的最长单词来解决这个问题。但是问题开始困扰我们这些问题......
shareasale => share as ale(wrong as 'ale' not in the dictionary)
shareasale => share a sale(correct)
Assuming 'share', 'a', 'sale' are all words in the dictionary unlike 'ale'.
我试图通过删除遇到错误之前找到的有效段来解决这个问题,即
shareasale => 'share' and 'as' (error = 'ale')
并从字典中删除一次,然后解决问题。所以
shareasale => no valid segments when share is removed
shareasale => share a sale (when 'as' is removed from the dictionary.
因此我也设法解决了这个问题。但后来我无法解决这个问题
asignas => 'as' ( error = 'ignas')
然后我的解决方案将从字典中删除'as'并尝试解决它
asignas => 'a' 'sign' (error = 'as')
因为在新的递归调用中,'as' 已从字典中删除。我写的函数在这个链接中。我希望有人可以通过它并帮助我找到更好的算法来解决这个问题,否则建议修改我现有的算法。