我需要將字符串拆分爲單詞,以使每個單詞來自字典。還要確保選擇左側最長的單詞。因此文本分割:將輸入與字典中最長單詞匹配的算法
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')
我的解決方案,然後會從字典中刪除「爲」,並試圖解決它
asignas => 'a' 'sign' (error = 'as')
因爲在新的遞歸調用「爲」已被刪除從字典中。我寫的功能是in this link。我希望有人可以通過它,並幫助我找到一個更好的算法來解決這個問題,建議修改我現有的算法。
謝謝@Jakub!儘管Photon的答案解決了我的問題,但這個答案幫助我更好地理解了解決方案,並提供了明確的解釋。 –