-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path0443-string-compression.rb
More file actions
51 lines (39 loc) · 877 Bytes
/
0443-string-compression.rb
File metadata and controls
51 lines (39 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true
# 443. String Compression
# https://leetcode.com/problems/string-compression
# @param {Character[]} chars
# @return {Integer}
def compress(chars)
n = chars.length
return 1 if n == 1
i = 0
j = 0
count = 0
while i < n do
count += 1
if chars[i + 1] != chars[i]
chars[j] = chars[i]
j += 1
if count > 1
count.to_s.each_char do |char|
chars[j] = char
j += 1
end
end
count = 0
end
i += 1
end
j
end
# **************** #
# TEST #
# **************** #
require "test/unit"
class Test_compress < Test::Unit::TestCase
def test_
assert_equal 6, compress(["a", "a", "b", "b", "c", "c", "c"])
assert_equal 1, compress(["a"])
assert_equal 4, compress(["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"])
end
end