[Swift]LeetCode828. 独特字符串 | Unique Letter String

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-vjmjjtyv-me.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

A character is unique in string S if it occurs exactly once in it.git

For example, in string S = "LETTER", the only unique characters are "L" and "R".github

Let's define UNIQ(S) as the number of unique characters in string S.数组

For example, UNIQ("LETTER") =  2.微信

Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S.ide

If there are two or more equal substrings at different positions in S, we consider them different.函数

Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.spa

Example 1:code

Input: "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10

Example 2:htm

Input: "ABA"
Output: 8
Explanation: The same as example 1, except uni("ABA") = 1.

Note: 0 <= S.length <= 10000.


若是一个字符在字符串 S 中有且仅有出现一次,那么咱们称其为独特字符。

例如,在字符串 S = "LETTER" 中,"L" 和 "R" 能够被称为独特字符。

咱们再定义 UNIQ(S) 做为字符串 S 中独特字符的个数。

那么,在 S = "LETTER" 中, UNIQ("LETTER") =  2

对于给定字符串 S,计算其全部非空子串的独特字符的个数,即 UNIQ(substring)

若是出现两个或者多个相同的子串,将其认为是不一样的两个子串。

考虑到答案可能会很是大,规定返回格式为:结果 mod 10 ^ 9 + 7

示例 1:

输入: "ABC"
输出: 10
解释: 全部可能的子串为:"A","B","C","AB","BC" 和 "ABC"。
     其中,每个子串都由独特字符构成。
     因此其长度总和为:1 + 1 + 1 + 2 + 2 + 3 = 10

示例 2:

输入: "ABA"
输出: 8
解释: 除了子串 UNIQ('ABA') = 1,其他与示例1相同。

说明: 0 <= S.length <= 10000


Runtime: 4344 ms
Memory Usage: 19.8 MB
 1 class Solution {
 2     func uniqueLetterString(_ S: String) -> Int {
 3         var index:[[Int]] = [[Int]](repeating:[Int](repeating:-1,count:2),count:26)
 4         var res:Int = 0
 5         var N:Int = S.count
 6         var mod:Int = Int(pow(10.0,9.0)) + 7
 7         for i in 0..<N
 8         {
 9             var c:Int = S[i].ascii - 65
10             res = (res + (i - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod
11             index[c] = [index[c][1], i]
12         }
13         for c in 0..<26
14         {
15             res = (res + (N - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod
16         }
17         return res
18     }
19 }
20 
21 //String扩展
22 extension String {        
23     //subscript函数能够检索数组中的值
24     //直接按照索引方式截取指定索引的字符
25     subscript (_ i: Int) -> Character {
26         //读取字符
27         get {return self[index(startIndex, offsetBy: i)]}
28     }
29 }
30 
31 //Character扩展 
32 extension Character  
33 {  
34   //Character转ASCII整数值(定义小写为整数值)
35    var ascii: Int {
36        get {
37            return Int(self.unicodeScalars.first?.value ?? 0)
38        }       
39     }
40 }