[Swift]LeetCode320. 通用簡寫 $ Generalized Abbreviation

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-fjhwgaxh-kh.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example:github

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"]

編寫一個函數來生成一個單詞的廣義縮寫。app

例子:函數

給定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測試spa

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"]
相關文章
相關標籤/搜索