#828

Count Unique Characters of All Substrings of a Given String

candidate master · 1340 · lc hard +32 · verified · 53.5% accepted · 2,251 likes · top 45%

Description

Define countUniqueChars(s) as the number of characters that appear exactly once in string s.

- For example, countUniqueChars("LEETCODE") = 5 because "L", "T", "C", "O", and "D" each appear only once.

Given a string s, return the total of countUniqueChars(t) summed over every non-empty substring t of s. The test cases guarantee the answer fits in a 32-bit integer.

Note that repeated substrings count as separate occurrences.

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

Code

1
2
3