Skip to content
本页目录

0828-统计子串中的唯一字符

题目描述

https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string

我们定义了一个函数 countUniqueChars(s) 来统计字符串 s 中的唯一字符,并返回唯一字符的个数。

例如:s = "LEETCODE" ,则其中 "L", "T","C","O","D" 都是唯一字符,因为它们只出现一次,所以 countUniqueChars(s) = 5 。

本题将会给你一个字符串 s ,我们需要返回 countUniqueChars(t) 的总和,其中 t 是 s 的子字符串。输入用例保证返回值为 32 位整数。

注意,某些子字符串可能是重复的,但你统计时也必须算上这些重复的子字符串(也就是说,你必须统计 s 的所有子字符串中的唯一字符)。

示例 1:

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

示例 2:

输入: s = "ABA"
输出: 8
解释: 除了 countUniqueChars("ABA") = 1 之外,其余与示例 1 相同。

示例 3:

输入:s = "LEETCODE"
输出:92

提示:

  • 1 <= s.length <= 10^5
  • s 只包含大写英文字符

思路:暴力法

分两部分,第一部分用dfs循环拆分子串,第二部分使用countUniqueChars统计子串的唯一字符个数,统计方法为使用hash表

算法复杂度 O(n^3) 会超时

csharp
public class Solution {

    private int countUniqueChars(string s){
        Dictionary<char,int> dict = new Dictionary<char,int>();
        for(int i=0; i<s.Length; i++){
            char c = s[i];
            dict[c] = dict.ContainsKey(c) ? dict[c] + 1 : 1;
        }
        int sum = 0;
        foreach(char key in dict.Keys){
            if(dict[key] == 1){
                sum++;
            }
        }
        return sum;
    }

    int total;

    private void dfs(string s, int startIndex){
        if(startIndex == s.Length){
            return;
        }
        for(int i=startIndex; i<s.Length; i++){
            string str = s.Substring(startIndex,i-startIndex+1);
            //Console.WriteLine(str);
            total += countUniqueChars(str);
        }
        dfs(s,startIndex+1);
    }

    public int UniqueLetterString(string s) {
        dfs(s,0);
        return total;
    }
}

思路:官方:TODO

如果不是唯一的字符,那么我们就可以不计算他 计算每个字符作为单个字符存在于字符串中的贡献值

csharp
public class Solution {
    public int UniqueLetterString(string s) {
        Dictionary<char, IList<int>> index = new Dictionary<char, IList<int>>();
        for (int i = 0; i < s.Length; i++) {
            if (!index.ContainsKey(s[i])) {
                index.Add(s[i], new List<int>());
                index[s[i]].Add(-1);
            }
            index[s[i]].Add(i);
        }
        int res = 0;
        foreach (KeyValuePair<char, IList<int>> pair in index) {
            IList<int> arr = pair.Value;
            arr.Add(s.Length);
            for (int i = 1; i < arr.Count - 1; i++) {
                res += (arr[i] - arr[i - 1]) * (arr[i + 1] - arr[i]);
            }
        }
        return res;
    }
}

Released under the MIT License.