[問題] LeetCode 472. Concatenated Words

看板Ruby作者 (沛納海)時間5年前 (2018/10/21 22:30), 編輯推噓4(403)
留言7則, 5人參與, 6年前最新討論串1/1
會 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 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.228.105.126 ※ 文章網址: https://www.ptt.cc/bbs/Ruby/M.1540132253.A.EF1.html

10/21 23:10, 5年前 , 1F
你的演算法是 O(n^3) ,Array#include? 改用Set 試試?
10/21 23:10, 1F

10/21 23:13, 5年前 , 2F
感覺建立一個 trie,再查詢會比較快
10/21 23:13, 2F

10/21 23:14, 5年前 , 3F
建立時間複雜度O(n*m),查詢是O(m),n是數量,m是長度
10/21 23:14, 3F

10/21 23:15, 5年前 , 4F
n*m應該不超過600000,m應該是60左右
10/21 23:15, 4F

10/22 02:42, 5年前 , 5F
TLE就是算法不夠好 可以看discuss票數最高的最佳解
10/22 02:42, 5F

05/16 13:07, 6年前 , 6F
我ruby新手 用ruby刷題會有什麼困難點要注意嗎
05/16 13:07, 6F

05/17 13:35, 6年前 , 7F
回樓上 時限有時候會很緊 一樣的算法用 C 寫會過 用 ruby
05/17 13:35, 7F
文章代碼(AID): #1Rp8sTxn (Ruby)
文章代碼(AID): #1Rp8sTxn (Ruby)