Skip to content

Commit 9f1caeb

Browse files
committedJan 4, 2025
Add solution #443
1 parent e13d211 commit 9f1caeb

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@
176176
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
177177
419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium|
178178
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
179+
443|[String Compression](./0443-string-compression.js)|Medium|
179180
448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy|
180181
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|
181182
452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium|

‎solutions/0443-string-compression.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 443. String Compression
3+
* https://leetcode.com/problems/string-compression/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of characters chars, compress it using the following algorithm:
7+
*
8+
* Begin with an empty string s. For each group of consecutive repeating characters in chars:
9+
* - If the group's length is 1, append the character to s.
10+
* - Otherwise, append the character followed by the group's length.
11+
*
12+
* The compressed string s should not be returned separately, but instead, be stored in the
13+
* input character array chars. Note that group lengths that are 10 or longer will be split
14+
* into multiple characters in chars.
15+
*
16+
* After you are done modifying the input array, return the new length of the array.
17+
*
18+
* You must write an algorithm that uses only constant extra space.
19+
*/
20+
21+
/**
22+
* @param {character[]} chars
23+
* @return {number}
24+
*/
25+
var compress = function(chars) {
26+
let pointer = 0;
27+
for (let i = 0; i < chars.length; i++) {
28+
const char = chars[i];
29+
let count = 0;
30+
while (i < chars.length && chars[i] === char) {
31+
count++;
32+
i++;
33+
}
34+
chars[pointer++] = char;
35+
if (count !== 1) {
36+
String(count).split('').forEach(n => chars[pointer++] = n);
37+
}
38+
i--;
39+
}
40+
chars.length = pointer;
41+
return pointer;
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.