Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e86e2dc

Browse files
authored
Create 271-Encode-and-Decode-Strings.rb
1 parent ac26cf7 commit e86e2dc

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

ruby/271-Encode-and-Decode-Strings.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Encodes a list of strings to a single string.
2+
#
3+
# @param {string[]} strs
4+
# @return {string}
5+
def encode(strs)
6+
strs.reduce('') do |acc, cur|
7+
"#{acc}\n#{cur.chars.map{_1.ord.to_s}.join(',')}"
8+
end[1..] + "\n"
9+
end
10+
11+
# Decodes a single string to a list of strings.
12+
#
13+
# @param {string} s
14+
# @return {string[]}
15+
def decode(s)
16+
s.each_line.map do |nums|
17+
nums[...-1].split(',').map(&:to_i).map(&:chr).join('')
18+
end
19+
end
20+
21+
22+
# Your functions will be called as such:
23+
# decode(encode(strs))

0 commit comments

Comments
 (0)