Created
June 10, 2018 15:53
-
-
Save deepakmahakale/af8eef07ff0cf88539938d5663ee1e1f to your computer and use it in GitHub Desktop.
StringValidator
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 StringValidator | |
ALLOWED_PARANTHESIS = { | |
')' => '(', | |
'}' => '{', | |
']' => '[' | |
}.freeze | |
def initialize(value = '') | |
@text = value | |
end | |
def valid? | |
!@text.empty? && balanced? | |
end | |
private | |
def balanced? | |
bracket_stack = [] | |
@text.each_char do |char| | |
if ALLOWED_PARANTHESIS.value?(char) | |
bracket_stack << char | |
elsif ALLOWED_PARANTHESIS.key?(char) | |
return false unless bracket_stack.pop == ALLOWED_PARANTHESIS[char] | |
else | |
# has only other matching parenthesis in between | |
return false | |
end | |
end | |
bracket_stack.empty? | |
end | |
end | |
loop do | |
puts 'Enter the input string: (type "exit" to leave)' | |
input = gets.chomp | |
break if input == 'exit' | |
string = StringValidator.new(input) | |
# String just because of the required output is 'True' and 'False' | |
puts string.valid? ? 'True' : 'False' | |
end | |
> ruby validate_string.rb | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ()[]{} | |
#=> True | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ([{}]) | |
#=> True | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ([]{}) | |
#=> True | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ([)] | |
#=> False | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ([] | |
#=> False | |
#=> Enter the input string: (type "exit" to leave) | |
#=> []) | |
#=> False | |
#=> Enter the input string: (type "exit" to leave) | |
#=> ([}) | |
#=> False | |
#=> Enter the input string: (type "exit" to leave) | |
#=> exit | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment