Skip to content

Commit a14235a

Browse files
committed
Add solution #828
1 parent ed88f60 commit a14235a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,7 @@
636636
825|[Friends Of Appropriate Ages](./0825-friends-of-appropriate-ages.js)|Medium|
637637
826|[Most Profit Assigning Work](./0826-most-profit-assigning-work.js)|Medium|
638638
827|[Making A Large Island](./0827-making-a-large-island.js)|Hard|
639+
828|[Count Unique Characters of All Substrings of a Given String](./0828-count-unique-characters-of-all-substrings-of-a-given-string.js)|Hard|
639640
830|[Positions of Large Groups](./0830-positions-of-large-groups.js)|Easy|
640641
831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium|
641642
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 828. Count Unique Characters of All Substrings of a Given String
3+
* https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/
4+
* Difficulty: Hard
5+
*
6+
* Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
7+
* - For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are
8+
* the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
9+
*
10+
* Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test
11+
* cases are generated such that the answer fits in a 32-bit integer.
12+
*
13+
* Notice that some substrings can be repeated so in this case you have to count the repeated
14+
* ones too.
15+
*/
16+
17+
/**
18+
* @param {string} s
19+
* @return {number}
20+
*/
21+
var uniqueLetterString = function(s) {
22+
const n = s.length;
23+
const lastPositions = {};
24+
let result = 0;
25+
26+
for (let i = 0; i < n; i++) {
27+
const char = s[i];
28+
if (!lastPositions[char]) lastPositions[char] = [-1, -1];
29+
30+
const [prevPrev, prev] = lastPositions[char];
31+
result += (i - prev) * (prev - prevPrev);
32+
lastPositions[char] = [prev, i];
33+
}
34+
35+
for (const char of Object.keys(lastPositions)) {
36+
const [prev, pos] = lastPositions[char];
37+
if (pos >= 0) result += (n - pos) * (pos - prev);
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)