-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
38 lines (32 loc) · 953 Bytes
/
test.js
File metadata and controls
38 lines (32 loc) · 953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function encodeString(inputStr) {
// Validate input
if (!/^[A-Z]+$/.test(inputStr)) {
return "Invalid String";
}
let result = "";
let charCount = {};
for (let i = 0; i < inputStr.length; i++) {
const currentChar = inputStr[i];
// Count consecutive occurrences of the current character
let count = 1;
while (i + 1 < inputStr.length && currentChar === inputStr[i + 1]) {
i++;
count++;
}
// Encode the character and its count
if (!charCount[currentChar]) {
charCount[currentChar] = 1;
} else {
charCount[currentChar]++;
}
result += currentChar;
if (count > 1) {
result += charCount[currentChar].toString();
}
}
return result;
}
// Example usage:
const inputStr = "WIINNNGGIIFFFFFFFYYYY";
const outputStr = encodeString(inputStr);
console.log(outputStr);