package com.算法专练.力扣.统计子串中的唯一字符;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author xnl
* @Description:
* @date: 2022/9/6 21:36
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String str = "ABA";
System.out.println(solution.uniqueLetterString(str));
}
public int uniqueLetterString(String s) {
Map<Character, List<Integer>> index = new HashMap<>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (!index.containsKey(c)){
index.put(c, new ArrayList<>());
index.get(c).add(-1);
}
index.get(c).add(i);
}
int res = 0;
for (Map.Entry<Character, List<Integer>> entry : index.entrySet()) {
List<Integer> value = entry.getValue();
value.add(s.length());
for (int i = 1; i < value.size() - 1; i++){
res += (value.get(i) - value.get(i - 1) ) * (value.get(i + 1) - value.get(i));
}
}
return res;
}
}
力扣:828. 统计子串中的唯一字符
统计字符串中唯一字符的出现区间
最新推荐文章于 2025-11-24 14:44:53 发布
本文介绍了一个Java解决方案,通过使用HashMap来追踪字符串中每个字符及其在字符串中的起始和结束位置,计算唯一字符连续子串的区间和。

740

被折叠的 条评论
为什么被折叠?



