题目来源:https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string/
大致题意:
给一个字符串,求该字符串所有子串中的唯一字符的个数和。
比如有字符串 ABC,其子串有 A、B、C、AB、BC、ABC,其中唯一字符的个数为 1、1、1、2、2、3,那么唯一字符的个数和为 10
思路
对于一个字符 ch 来说,如果能求出其作为唯一字符出现的子串的数目,那么就可以求得该字符对答案贡献值。
假设某个字符串出现位置为 idx,那么求某个字符出现的子串数目,可以通过先求出该字符左右两侧第一个和其相同字符出现的位置 left 和right,然后通过公式计算得出该字符作为唯一字符的子串个数:(idx - left) * (right - idx) 。这也是该位置字符对答案的贡献值
于是可以使用 list 存下相同字符出现的索引,对于某个字符对应的 list 来说,可以通过遍历 list 求得字符串中该字符对答案的贡献值,对于第 i 个元素,也就是 list[i] 处字符对答案的贡献值可以通过以下方法算出:
- (list[i] - list[i - 1]) * (list[i + 1] - list[i])
遍历所有 list 即可求出答案
代码:
public int uniqueLetterString(String s) {
int ans = 0;
int n = s.length();
// 存字符对应的 list,list 是该字符出现的所有索引
Map<Character, List<Integer>> idxMap = new HashMap<>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
// 获取该字符对应的 list
List<Integer> idxList = idxMap.getOrDefault(ch, new ArrayList<>());
idxList.add(i); // 将当前索引放入 list
idxMap.putIfAbsent(ch, idxList);
}
// 遍历所有 list
for (List<Integer> list : idxMap.values()) {
// 存字符上一个出现的位置,初始时左侧没有相同字符,初始化为 -1
int last = -1;
int size = list.size();
// 计算每个位置字符的贡献值
for (int i = 0; i < size - 1; i++) {
ans += (list.get(i) - last) * (list.get(i + 1) - list.get(i));
last = list.get(i);
}
ans += (list.get(size - 1) - last) * (n - list.get(size - 1));
}
return ans;
}