File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 176
176
414|[ Third Maximum Number] ( ./0414-third-maximum-number.js ) |Easy|
177
177
419|[ Battleships in a Board] ( ./0419-battleships-in-a-board.js ) |Medium|
178
178
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|
179
180
448|[ Find All Numbers Disappeared in an Array] ( ./0448-find-all-numbers-disappeared-in-an-array.js ) |Easy|
180
181
451|[ Sort Characters By Frequency] ( ./0451-sort-characters-by-frequency.js ) |Medium|
181
182
452|[ Minimum Number of Arrows to Burst Balloons] ( ./0452-minimum-number-of-arrows-to-burst-balloons.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments