Skip to content

Commit 92a0738

Browse files
authored
Create String Compression.py
1 parent 6830972 commit 92a0738

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

String Compression.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
'''
2+
Given an array of characters, compress it in-place.
3+
4+
The length after compression must always be smaller than or equal to the original array.
5+
6+
Every element of the array should be a character (not int) of length 1.
7+
8+
After you are done modifying the input array in-place, return the new length of the array.
9+
10+
11+
Follow up:
12+
Could you solve it using only O(1) extra space?
13+
14+
15+
Example 1:
16+
Input:
17+
["a","a","b","b","c","c","c"]
18+
19+
Output:
20+
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
21+
22+
Explanation:
23+
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
24+
Example 2:
25+
Input:
26+
["a"]
27+
28+
Output:
29+
Return 1, and the first 1 characters of the input array should be: ["a"]
30+
31+
Explanation:
32+
Nothing is replaced.
33+
Example 3:
34+
Input:
35+
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
36+
37+
Output:
38+
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
39+
40+
Explanation:
41+
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
42+
Notice each digit has it's own entry in the array.
43+
Note:
44+
All characters have an ASCII value in [35, 126].
45+
1 <= len(chars) <= 1000.
46+
'''
47+
48+
class Solution(object):
49+
def compress(self, chars):
50+
"""
51+
:type chars: List[str]
52+
:rtype: int
53+
"""
54+
ans = []
55+
start = 0
56+
end = start
57+
while start < len(chars):
58+
while end + 1 < len(chars) and chars[end + 1] == chars[start]:
59+
end += 1
60+
ans.append(chars[start])
61+
if end != start:
62+
ans += self.getStrArrayFromInt(end - start + 1)
63+
start = end + 1
64+
65+
for i in xrange(len(ans)):
66+
chars[i] = ans[i]
67+
return len(ans)
68+
69+
def getStrArrayFromInt(self, num):
70+
res = []
71+
while num > 0:
72+
res = [str(num % 10)] + res
73+
num //= 10
74+
return res

0 commit comments

Comments
 (0)