Commit 8ba0da8

mo khan <mo.khan@gmail.com>
2020-08-13 19:42:58
Solve brace matching with a stack
1 parent 13d551e
Changed files (1)
2020
08
2020/08/13/main.rb
@@ -0,0 +1,54 @@
+def assert_equal(x, y)
+  raise "Expected #{x.inspect}, Got #{y.inspect}" unless x == y
+end
+
+=begin
+
+stack:
+
+---
+|[|
+---
+|{|
+---
+|(|
+---
+
+       x
+|(|{|[|)|]|
+=end
+
+
+class Solution
+  MATCHES = {
+    '(' => ')',
+    '[' => ']',
+    '{' => '}'
+  }.freeze
+
+  # space: O(n)
+  # time: O(n)
+  def self.run(input)
+    stack = []
+
+    for current in input.chars
+      if MATCHES[current]
+        stack.push(current)
+      elsif current == MATCHES[stack[-1]]
+        stack.pop
+      else
+        break
+      end
+    end
+
+    stack.empty?
+  end
+end
+
+assert_equal true, Solution.run("((()))")
+assert_equal true, Solution.run("[()]{}")
+assert_equal false, Solution.run("({[)]")
+assert_equal false, Solution.run("()(){(())")
+assert_equal true, Solution.run("")
+assert_equal true, Solution.run("([{}])()")
+puts "Yay!"