Last active
June 16, 2016 14:38
-
-
Save J3RN/03c030f4347642f3fd0c4068e28144a9 to your computer and use it in GitHub Desktop.
Another balanced parens parser
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
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 |
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
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 |
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
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