File tree 1 file changed +9
-22
lines changed
Chap_1_Arrays_and_Strings
1 file changed +9
-22
lines changed Original file line number Diff line number Diff line change 1
1
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
12
8
else
13
- container << Array . new
14
- container [ - 1 ] << letter
9
+ compressed_string << " #{ char } #{ count } "
10
+ count = 1
15
11
end
16
12
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
27
14
end
You can’t perform that action at this time.
0 commit comments