Created
December 26, 2022 03:27
-
-
Save dharshan/c8055f31f261d45c3ee314829b78e7a4 to your computer and use it in GitHub Desktop.
Ruby bracket matching using stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BracketDemo | |
def solution(str) | |
valid = true | |
stack = [] | |
str.each_char do |char| | |
case char | |
when '[', '{', '(' | |
stack.push(char) | |
when ']' | |
last = stack.pop | |
valid = false if last != '[' | |
when ')' | |
last = stack.pop | |
valid = false if last != '(' | |
when '}' | |
last = stack.pop | |
valid = false if last != '{' | |
end | |
end | |
valid && stack.empty? ? 1 : 0 | |
end | |
end | |
puts BracketDemo.new.solution("[]}()") | |
puts BracketDemo.new.solution("[]{}()") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment