★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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
。
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 }