[Swift]LeetCode940. 不一樣的子序列 II | Distinct Subsequences II

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

Given a string S, count the number of distinct, non-empty subsequences of S .git

Since the result may be large, return the answer modulo 10^9 + 7.github

Example 1:微信

Input: "abc"
Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". 

Example 2:app

Input: "aba"
Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba". 

Example 3:spa

Input: "aaa"
Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".

Note:code

  1. S contains only lowercase letters.
  2. 1 <= S.length <= 2000

給定一個字符串 S,計算 S 的不一樣非空子序列的個數。htm

由於結果可能很大,因此返回答案模 10^9 + 7.blog

示例 1:ci

輸入:"abc"
輸出:7
解釋:7 個不一樣的子序列分別是 "a", "b", "c", "ab", "ac", "bc", 以及 "abc"。

示例 2:

輸入:"aba"
輸出:6
解釋:6 個不一樣的子序列分別是 "a", "b", "ab", "ba", "aa" 以及 "aba"。

示例 3:

輸入:"aaa"
輸出:3
解釋:3 個不一樣的子序列分別是 "a", "aa" 以及 "aaa"。

提示:

  1. S 只包含小寫字母。
  2. 1 <= S.length <= 2000

28ms
 1 class Solution {
 2     func distinctSubseqII(_ S: String) -> Int {
 3         return distinctSubsequence(S.toCharArray(), 1000000007)
 4     }
 5     
 6     func distinctSubsequence(_ a:[Character],_ mod:Int) -> Int
 7     {
 8         var n = a.count
 9         var bucket:[Int] = [Int](repeating: -1,count: 26)
10         
11         var cum:Int = 0
12         for i in 0..<n
13         {
14             var v:Int = cum
15             //'a'的ASCII碼值:97
16             var ind:Int = a[i].ascii - 97
17             if bucket[ind] == -1
18             {
19                 v += 1
20             }
21             else
22             {
23                 v += mod - bucket[ind]
24             }
25             if v >= mod
26             { 
27                 v -= mod
28             }
29             bucket[ind] = cum
30             cum += v
31             if cum >= mod
32             {
33                 cum -= mod
34             }
35         }
36         return cum
37     }
38 }
39 
40 //String擴展方法
41 extension String {
42     func toCharArray() -> [Character]
43     {
44         var arr:[Character] = [Character]()
45         for char in self.characters
46         {
47             arr.append(char)
48         }
49         return arr
50     }
51 }
52 
53 //Character擴展方法  
54 extension Character  
55 {  
56   //轉ASCII整數值(定義小寫爲整數值)
57    var ascii: Int {
58         get {
59             let s = String(self).unicodeScalars
60             return Int(s[s.startIndex].value)
61         }
62     }
63 }
相關文章
相關標籤/搜索