[問題] LeetCode 472. Concatenated Words

作者: paneraii (沛納海)   2018-10-21 22:30:51
會 time limit exceeded,求高手指點
def find_all_concatenated_words_in_a_dict(words)
return [] if words.count <= 1 || words.count > 10000 || words.map(&:to_s).inject(&:+).length > 600000
result = []
[*0...words.count].each do |i|
new_arr = words.dup
new_word = new_arr.delete(words[i]).dup
result << words[i] if concated_by_others?(new_word, new_arr)
end
return result
end
def concated_by_others?(str, arr)
[*1..str.length].each do |j|
if arr.include?(str.slice(0, j))
new_str = str.dup
new_str.slice!(str.slice(0, j))
return true if new_str.length.zero? or concated_by_others?(new_str, arr)
end
end
return false
end
作者: johnlinvc (阿翔)   2018-10-21 23:10:00
你的演算法是 O(n^3) ,Array#include? 改用Set 試試?
作者: mars90226 (火星人)   2018-10-21 23:13:00
感覺建立一個 trie,再查詢會比較快建立時間複雜度O(n*m),查詢是O(m),n是數量,m是長度n*m應該不超過600000,m應該是60左右
作者: matrixki (New Season)   2018-10-22 02:42:00
TLE就是算法不夠好 可以看discuss票數最高的最佳解
作者: lance8537 (小砰砰)   2017-05-16 13:07:00
我ruby新手 用ruby刷題會有什麼困難點要注意嗎
作者: b0w1d (zeta)   2017-05-17 13:35:00
回樓上 時限有時候會很緊 一樣的算法用 C 寫會過 用 ruby

Links booklink

Contact Us: admin [ a t ] ucptt.com