forked from AdaGold/stacks-queues
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathproblems.rb
More file actions
54 lines (47 loc) · 1 KB
/
problems.rb
File metadata and controls
54 lines (47 loc) · 1 KB
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
require_relative "./stack.rb"
def balanced(string)
return true if string == ""
parens_hash = {
"(" => ")",
"[" => "]",
"{" => "}",
}
stack_parens = Stack.new
string.each_char do |paren|
if parens_hash[paren]
stack_parens.push(parens_hash[paren])
else
return false if paren != stack_parens.pop
end
end
return stack_parens.empty?
end
def evaluate_postfix(postfix_expression)
operand_hash = {
"+" => true,
"-" => true,
"*" => true,
"/" => true,
}
stack_postfix = Stack.new
postfix_expression.each_char do |char|
if !operand_hash[char]
stack_postfix.push(char)
else
digit2 = stack_postfix.pop.to_i
digit1 = stack_postfix.pop.to_i
case char
when "+"
value = digit1 + digit2
when "-"
value = digit1 - digit2
when "*"
value = digit1 * digit2
when "/"
value = digit1 / digit2
end
stack_postfix.push(value)
end
end
return stack_postfix.pop
end