Skip to content

Commit c38e238

Browse files
committed
Lesson 5 - Nesting (from scratch)
1 parent 367449a commit c38e238

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

nesting.rb

+18-11
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
def nesting(s)
2-
opened = 0
2+
stack = []
33

4-
s.chars.each do |c|
5-
if c == '('
6-
opened += 1
4+
s.chars.each do |char|
5+
if char == '('
6+
stack << char
77
else
8-
return 0 if opened == 0
9-
opened -= 1
8+
return 0 if stack.pop != '('
109
end
1110
end
1211

13-
opened == 0 ? 1 : 0
12+
stack.empty? ? 1 : 0
1413
end
1514

1615
require 'minitest/autorun'
@@ -20,11 +19,19 @@ def test_example_input
2019
assert_equal 1, nesting('(()(())())')
2120
end
2221

23-
def test_unopened
24-
assert_equal 0, nesting('))')
22+
def test_example_fail
23+
assert_equal 0, nesting('())')
2524
end
2625

27-
def test_unclosed
28-
assert_equal 0, nesting('((')
26+
def test_empty
27+
assert_equal 1, nesting('')
28+
end
29+
30+
def test_success
31+
assert_equal 1, nesting('()()')
32+
end
33+
34+
def test_not_closed
35+
assert_equal 0, nesting('(())(')
2936
end
3037
end

0 commit comments

Comments
 (0)