统计子串中的唯一字符
难度:
标签:
题目描述
Let's define a function countUniqueChars(s)
that returns the number of unique characters in s
.
- For example, calling
countUniqueChars(s)
ifs = "LEETCODE"
then"L"
,"T"
,"C"
,"O"
,"D"
are the unique characters since they appear only once ins
, thereforecountUniqueChars(s) = 5
.
Given a string s
, return the sum of countUniqueChars(t)
where t
is a substring of s
. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Example 1:
Input: s = "ABC" Output: 10 Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars
("ABA") = 1.
Example 3:
Input: s = "LEETCODE" Output: 92
Constraints:
1 <= s.length <= 105
s
consists of uppercase English letters only.
代码结果
运行时间: 142 ms, 内存: 20.6 MB
解释
方法:
本题解使用了哈希表(字典)来统计字符串中每个字符的所有出现索引。对于每个字符,我们将字符在字符串中的所有索引存储在一个列表中,并额外在每个列表的末尾添加字符串长度作为边界。接着,针对每个字符的索引列表,计算每个字符在其每个出现位置的唯一性对于子字符串的贡献。具体方法是,对于列表中的每个索引,计算该索引与前一个索引之间的差值,并乘以该索引与下一个索引之间的差值。这样计算的结果即为该字符对所有子字符串中的唯一字符数的总贡献。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在每个字符的索引列表末尾添加字符串长度作为边界,这一操作有什么特别的含义或作用?
▷🦆
在计算每个字符对子字符串唯一性的贡献时,`(c - l + 1) * (r - c)` 这个计算公式是如何得出的?请问这里的每个变量代表什么意义?
▷🦆
算法中提到的`遍历字符串并构建字符的索引列表`的过程能否详细解释一下,尤其是如何处理字符重复出现的情况?
▷