-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path07-1-brackets_spec.rb
94 lines (86 loc) · 1.72 KB
/
07-1-brackets_spec.rb
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# https://app.codility.com/demo/results/trainingJW3BU4-E8H/
def solution(s)
stack = []
hash = {'{' => '}', '(' => ')', '[' => ']'}
s.each_char do |char|
if hash[stack.last] == char
stack.pop
else
stack << char
end
end
return 0 if stack.size > 0
1
end
# Golang version:
# https://www.hackerrank.com/challenges/balanced-brackets/problem
# func isBalanced(s string) string {
# stack := []string{}
# hash := map[string]string{
# "(": ")",
# "[": "]",
# "{": "}",
# }
# var top string
# for _, char := range strings.Split(s, "") {
# if len(stack) > 0 {
# top = stack[len(stack)-1]
# } else {
# top = ""
# }
# if hash[top] == char {
# stack = stack[:len(stack)-1] // pop off stack
# } else {
# stack = append(stack, char)
# }
# }
# if len(stack) > 0 {
# return "NO"
# }
# return "YES"
# }
describe '#brackets' do
it 'returns 1 if brackets are properly nested' do
expect(solution("{[()()]}")).to eq 1
end
it 'returns 0 if they are not' do
expect(solution("([)()]")).to eq 0
end
end
# char = {
# stack: ["{"]
# char = [
# stack: ["{", "["]
# char = (
# stack: ["{", "[", "("]
# char = )
# pop ( )
# stack: ["{", "["]
# char = (
# stack: ["{", "[", "("]
# char = )
# pop ( )
# stack: ["{", "["]
# char = ]
# pop [ ]
# stack: ["{"]
# char = }
# pop { }
# stack: []
# final stack: []
# 1
# char = (
# stack: ["("]
# char = [
# stack: ["(", "["]
# char = )
# stack: ["(", "[", ")"]
# char = (
# stack: ["(", "[", ")", "("]
# char = )
# pop ( )
# stack: ["(", "[", ")"]
# char = ]
# stack: ["(", "[", ")", "]"]
# final stack: ["(", "[", ")", "]"]
# 0