Skip to content

Commit e65b258

Browse files
committed
String Compression
1 parent ae647ca commit e65b258

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

String_Compression.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Given an array of characters, compress it in-place.
2+
#
3+
# The length after compression must always be smaller than or equal to the original array.
4+
#
5+
# Every element of the array should be a character (not int) of length 1.
6+
#
7+
# After you are done modifying the input array in-place, return the new length of the array.
8+
#
9+
# Follow up:
10+
# Could you solve it using only O(1) extra space?
11+
#
12+
# Input:
13+
# ["a","a","b","b","c","c","c"]
14+
#
15+
# Output:
16+
# Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
17+
#
18+
# Explanation:
19+
# "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
20+
#
21+
#
22+
# Input:
23+
# ["a"]
24+
#
25+
# Output:
26+
# Return 1, and the first 1 characters of the input array should be: ["a"]
27+
#
28+
# Explanation:
29+
# Nothing is replaced.
30+
#
31+
#
32+
# Input:
33+
# ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
34+
#
35+
# Output:
36+
# Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
37+
#
38+
# Explanation:
39+
# Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
40+
# Notice each digit has it's own entry in the array
41+
42+
43+
class Solution:
44+
def compress(self, chars):
45+
n = len(chars)
46+
i = 0
47+
count = 1
48+
for j in range(1, n + 1):
49+
if j < n and chars[j] == chars[j - 1]:
50+
count += 1
51+
else:
52+
chars[i] = chars[j - 1]
53+
i += 1
54+
if count > 1:
55+
for d in str(count):
56+
chars[i] = d
57+
i += 1
58+
count = 1
59+
return i

0 commit comments

Comments
 (0)