大佬教程收集整理的这篇文章主要介绍了[Swift]LeetCode472. 连接词 | Concatenated Words,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Given a list of words (without duplicates),please write a program that returns all concatenated words in the given list of words.
A concatenated word is defined as a String that is comprised entirely of at least two shorter words in the given array.
Example:
Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","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
.给定一个不含重复单词的列表,编写一个程序,返回给定单词列表中所有的连接词。
连接词的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。
示例:
输入: ["cat","ratcatdogcat"] 输出: ["catsdogcats","ratcatdogcat"] 解释: "catsdogcats"由"cats","dog" 和 "cats"组成; "dogcatsdog"由"dog","cats"和"dog"组成; "ratcatdogcat"由"rat","dog"和"cat"组成。
说明:
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 }
以上是大佬教程为你收集整理的[Swift]LeetCode472. 连接词 | Concatenated Words全部内容,希望文章能够帮你解决[Swift]LeetCode472. 连接词 | Concatenated Words所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。