Last active
March 8, 2017 09:35
-
-
Save tareksamni/50f09cf876f4563d505f0d38b546058b to your computer and use it in GitHub Desktop.
check balanced brackets
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
# 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