Skip to content

Instantly share code, notes, and snippets.

@srinidhi-lwt
Created June 1, 2018 07:27
Show Gist options
  • Save srinidhi-lwt/90f8c6b18294866f601547a252269321 to your computer and use it in GitHub Desktop.
Save srinidhi-lwt/90f8c6b18294866f601547a252269321 to your computer and use it in GitHub Desktop.
class InterviewTest
def balanced?(string)
return false if string.length.odd? or string.blank?
res = []
string.split('').each do |char|
if opening_brackets.include?(char)
res << char
elsif matching_brackets[res[-1]] == char
res.pop
else
return false
end
end
res.present? ? false : true
end
private
def opening_brackets
['(', '{', '[']
end
def matching_brackets
{
'(' => ')',
'[' => ']',
'{' => '}'
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment