★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-syaozcqt-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.git
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.github
Example:數組
Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Note:微信
10,000
600,000
.給定一個不含重複單詞的列表,編寫一個程序,返回給定單詞列表中全部的鏈接詞。app
鏈接詞的定義爲:一個字符串徹底是由至少兩個給定數組中的單詞組成的。spa
示例:code
輸入: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] 輸出: ["catsdogcats","dogcatsdog","ratcatdogcat"] 解釋: "catsdogcats"由"cats", "dog" 和 "cats"組成; "dogcatsdog"由"dog", "cats"和"dog"組成; "ratcatdogcat"由"rat", "cat", "dog"和"cat"組成。
說明:htm
10000
。600000
。1 class Solution { 2 func findAllConcatenatedWordsInADict(_ words: [String]) -> [String] { 3 var res:[String] = [String]() 4 var dict:Set<String> = Set(words) 5 for word in words 6 { 7 var n:Int = word.count 8 if n == 0 {continue} 9 var dp:[Bool] = [Bool](repeating:false,count:n + 1) 10 dp[0] = true 11 for i in 0..<n 12 { 13 if !dp[i] {continue} 14 for j in (i + 1)...n 15 { 16 var str:String = word.subString(i, j - i) 17 if j - i < n && dict.contains(str) 18 { 19 dp[j] = true 20 } 21 } 22 if dp[n] 23 { 24 res.append(word) 25 break 26 } 27 } 28 } 29 return res 30 } 31 } 32 33 extension String { 34 // 截取字符串:指定索引和字符數 35 // - begin: 開始截取處索引 36 // - count: 截取的字符數量 37 func subString(_ begin:Int,_ count:Int) -> String { 38 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 39 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 40 return String(self[start..<end]) 41 } 42 }