Skip to content

Instantly share code, notes, and snippets.

@tareksamni
Last active March 8, 2017 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tareksamni/50f09cf876f4563d505f0d38b546058b to your computer and use it in GitHub Desktop.
Save tareksamni/50f09cf876f4563d505f0d38b546058b to your computer and use it in GitHub Desktop.
check balanced brackets
# Just another easy interview question in Ruby
# Description: https://www.hackerrank.com/challenges/balanced-brackets
# This solution is also expecting other chars other than the brackets
POSSIBLE_BRACKETS = %w({ } [ ] < > \( \)).freeze
MATCHING_BRACKETS = {
'{' => '}',
'[' => ']',
'<' => '>',
'(' => ')'
}.freeze
def balanced_brackets?(str)
stack = []
# WRITE YOUR CODE HERE
str.split('').each do |char|
next unless POSSIBLE_BRACKETS.include?(char)
stack.push(char) && next if MATCHING_BRACKETS.keys.include?(char)
return 0 if char != MATCHING_BRACKETS[stack.pop]
end
stack.empty? ? 1 : 0
end
puts balanced_brackets?('}{><')
puts balanced_brackets?('{qwe}eqweqP{1231312[312312]}312312{<<>>}[][]')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment