Skip to content

Instantly share code, notes, and snippets.

@J3RN
Last active June 16, 2016 14:38
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 J3RN/03c030f4347642f3fd0c4068e28144a9 to your computer and use it in GitHub Desktop.
Save J3RN/03c030f4347642f3fd0c4068e28144a9 to your computer and use it in GitHub Desktop.
Another balanced parens parser
class Parser
ENCLOSURES = {
'"' => '"',
'(' => ')',
'{' => '}',
'[' => ']'
}
def initialize
@i = 0
end
def is_valid? str
return false unless ENCLOSURES.keys.include? str[@i]
close = ENCLOSURES[str[@i]]
@i += 1
valid = true
while str[@i] != close && @i != str.length && valid
valid = is_valid? str
@i += 1
end
return valid && str[@i] == close
end
end
class Parser
ENCLOSURES = {
'"' => '"',
'(' => ')',
'{' => '}',
'[' => ']'
}
def initialize
@i = 0
end
def is_valid? str
return true if @i >= str.length
return false unless ENCLOSURES.keys.include? str[@i]
close = ENCLOSURES[str[@i]]
@i += 1
while is_valid? str
@i += 1
end
actual_close = str[@i]
@i += 1
return actual_close == close && is_valid?(str)
end
end
class Parser
ENCLOSURES = {
'"' => '"',
'(' => ')',
'{' => '}',
'[' => ']'
}
def initialize
@i = 0
end
def is_beginning? str
return ENCLOSURES.key? str[@i]
end
def is_valid? str
return true if @i >= str.length
return false unless is_beginning? str
valid = true
while is_beginning?(str) && valid
close = ENCLOSURES[str[@i]]
@i += 1
is_valid?(str)
actual_close = str[@i]
@i += 1
valid &&= actual_close == close
end
return valid
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment