Middle
You need to count the number of consecutive characters, but preserving the order of unique characters.
sobes.tech AI
Answer from AI
To count the number of consecutive characters while preserving the order of appearance of unique characters, you need to iterate through the string and count the length of each sequence of identical characters in a row. For example, for the string "aaabbc", the result will be: a:3, b:2, c:1.
Here's an example implementation of the function:
function countSymbols(str) {
const result = new Map();
let prevChar = null;
let count = 0;
for (const ch of str) {
if (ch === prevChar) {
count++;
} else {
if (prevChar !== null) {
result.set(prevChar, (result.get(prevChar) || 0) + count);
}
prevChar = ch;
count = 1;
}
}
// Add the last character
if (prevChar !== null) {
result.set(prevChar, (result.get(prevChar) || 0) + count);
}
return result;
}
// Example usage:
const counts = countSymbols("aaabbcaaa");
for (const [char, cnt] of counts) {
console.log(`${char}: ${cnt}`);
}
// Output:
// a: 6
// b: 2
// c: 1
In this code, we accumulate the count of consecutive characters and sum them for each unique character, preserving the order of appearance in a Map.