Skip to content

Instantly share code, notes, and snippets.

@dotconde
Created November 27, 2021 04:02
Show Gist options
  • Save dotconde/882aff0374611fbb5d554f765f53ce72 to your computer and use it in GitHub Desktop.
Save dotconde/882aff0374611fbb5d554f765f53ce72 to your computer and use it in GitHub Desktop.
String balancer
# frozen_string_literal: true
class Message
def initialize(content)
@content = content
end
def balanced?
return false unless allowed_string?(@content)
content_dup = @content.dup
if content_dup[0] == '(' && content_dup[-1] == ')'
remove_side_brackets(content_dup)
end
sanitized_content = remove_emoji(content_dup)
stack = []
sanitized_content.each_char do |ch|
case ch
when '('
stack << ch
when ')'
return false if stack.empty?
stack.pop
end
end
stack.empty?
end
def allowed_string?(msg)
msg.each_char do |char|
return false unless valid_char?(char)
end
end
def valid_char?(char)
!!(char =~ /^[a-z\s.:.).(]/)
end
def remove_side_brackets(content)
content[0] = ''
content[content.size - 1] = ''
content
end
def remove_emoji(msg)
msg.gsub(':)', '')
.gsub(':(', '')
end
end
# Test cases
test_cases = ['hola', '(hola)', '(()', '(:)', 'no voy (:()', 'hoy pm: fiesta :):)', ':((', 'a (b (c (d) c) b) a :)']
test_cases.each { |tc| puts Message.new(tc).balanced? }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment