为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode320. 通用简写 $ Generalized Abbreviation

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10706726.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Write a function to generate the generalized abbreviations of a word.

Example:

Given word = "word", return the following list (order does not matter):

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

编写一个函数来生成一个单词的广义缩写。

例子:

给定word = "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"]

 

posted @ 2019-04-14 20:06  为敢技术  阅读(319)  评论(0编辑  收藏  举报