在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Write a function to generate the generalized abbreviations of a word. Example: Given word = ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 编写一个函数来生成一个单词的广义缩写。 例子: 给定word = ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] Solution: 1 class Solution { 2 func generateAbbreviations(_ word:String) -> [String] { 3 var res:[String] = [String]() 4 var str:String = String() 5 if !word.isEmpty 6 { 7 str = String(word.count) 8 } 9 res.append(str) 10 for i in 0..<word.count 11 { 12 let arr:[String] = generateAbbreviations(word.subString(i + 1)) 13 for a in arr 14 { 15 var left:String = String() 16 if i > 0 17 { 18 left = String(i) 19 } 20 res.append(left + word.subString(i, 1) + a ) 21 } 22 } 23 return res 24 } 25 } 26 27 extension String { 28 // 截取字符串:从index到结束处 29 // - Parameter index: 开始索引 30 // - Returns: 子字符串 31 func subString(_ index: Int) -> String { 32 let theIndex = self.index(self.endIndex, offsetBy: index - self.count) 33 return String(self[theIndex..<endIndex]) 34 } 35 36 // 截取字符串:指定索引和字符数 37 // - begin: 开始截取处索引 38 // - count: 截取的字符数量 39 func subString(_ begin:Int,_ count:Int) -> String { 40 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 41 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 42 return String(self[start..<end]) 43 } 44 } 点击:Playground测试 1 var sol = Solution() 2 print(sol.generateAbbreviations("word")) 3 //Print ["4", "w3", "wo2", "wor1", "word", "wo1d", "w1r1", "w1rd", "w2d", "1o2", "1or1", "1ord", "1o1d", "2r1", "2rd", "3d"]
|
请发表评论