You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md
+55-3
Original file line number
Diff line number
Diff line change
@@ -50,6 +50,18 @@ Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
50
50
51
51
## Solutions
52
52
53
+
**Solution 1: Calculate the Contribution of Each Character**
54
+
55
+
For each character $c_i$ in the string $s$, when it appears only once in a substring, it contributes to the count of unique characters in that substring.
56
+
57
+
Therefore, we only need to calculate for each character $c_i$, how many substrings contain this character only once.
58
+
59
+
We use a hash table or an array $d$ of length $26$, to store the positions of each character in $s$ in order of index.
60
+
61
+
For each character $c_i$, we iterate through each position $p$ in $d[c_i]$, find the adjacent positions $l$ on the left and $r$ on the right, then the number of substrings that meet the requirements by expanding from position $p$ to both sides is $(p - l) \times (r - p)$. We perform this operation for each character, add up the contributions of all characters, and get the answer.
62
+
63
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$.
0 commit comments