Skip to content

Commit d6ebab6

Browse files
committed
fix and update q1_06 string compression
1 parent b4eb20a commit d6ebab6

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,14 @@
11
def string_compression(string)
2-
container = [
3-
[]
4-
]
5-
word = string.split('')
6-
7-
word.each do |letter|
8-
if container[-1] == []
9-
container[-1] << letter
10-
elsif container[-1][0] == letter
11-
container[-1] << letter
2+
compressed_string = ''
3+
current = nil
4+
count = 1
5+
string.split('').each_with_index do |char, index|
6+
if char == string[index + 1]
7+
count += 1
128
else
13-
container << Array.new
14-
container[-1] << letter
9+
compressed_string << "#{char}#{count}"
10+
count = 1
1511
end
1612
end
17-
compressed = ""
18-
container.length.times do |count|
19-
compressed = compressed + container[count][0]+container[count].length.to_s
20-
end
21-
22-
if string.length <= compressed.length
23-
string
24-
else
25-
compressed
26-
end
13+
string.length <= compressed_string.length ? string : compressed_string
2714
end

0 commit comments

Comments
 (0)