-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathBrace.rb
71 lines (62 loc) · 1.84 KB
/
Brace.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
=begin
Write a function called validBraces that takes a string of braces, and
determines if the order of the braces is valid. validBraces should
return true if the string is valid, and false if it's invalid.
This Kata is similar to the Valid Parentheses Kata, but introduces
four new characters. Open and closed brackets, and open and closed
curly braces. Thanks to @arnedag for the idea!
All input strings will be nonempty, and will only consist of open
parentheses '(' , closed parentheses ')', open brackets '[',
closed brackets ']', open curly braces '{' and closed curly braces '}'.
What is considered Valid? A string of braces is considered valid
if all braces are matched with the correct brace.
For example:
'(){}[]' and '([{}])' would be considered valid, while '(}',
'[(])', and '[({})](]' would be considered invalid.
Examples:
validBraces( "(){}[]" ) => returns true
validBraces( "(}" ) => returns false
validBraces( "[(])" ) => returns false
validBraces( "([{}])" ) => returns true
=end
# My Solution
def validBraces(braces)
level = 0
check = []
braces.split("").each do |c|
if ['(','{','['].include? c
level += 1
check[level] = c
end
if c == ")" && check[level] == "("
level -= 1
elsif c == ")" && check[level] != "("
level += 10
end
if c == "}" && check[level] == "{"
level -= 1
elsif c == "}" && check[level] != "{"
level += 10
end
if c == "]" && check[level] == "["
level -= 1
elsif c == "]" && check[level] != "["
level += 10
end
end
level == 0 ? true : false
end
# Better Solution
def validBraces(braces)
while braces.gsub!(/(\(\)|\[\]|\{\})/,'') do; end
braces.empty?
end
# Another Solution
def validBraces(braces)
(braces.length / 2).times do |i|
braces.sub!("{}", "")
braces.sub!("[]", "")
braces.sub!("()", "")
end
braces.empty?
end