Created
June 9, 2018 21:42
-
-
Save Nitesh-Mishra/b80d72aa45c9b0a6ee0e7922d1041fee to your computer and use it in GitHub Desktop.
check balanced parentheses in ruby
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
# check balanced parentheses in ruby : | |
# | |
# $ ruby check_balanced_parentheses.rb | |
# Enter string : | |
# ((())) | |
# true | |
def check_balanced_parentheses?(entered_string) | |
stack = [] | |
entered_string.chars.each do |token| | |
case token | |
when '(' | |
stack.push '(' | |
when ')' | |
if stack.empty? || stack.pop != '(' | |
return false | |
end | |
end | |
end | |
stack.empty? | |
end | |
puts "Enter string :" | |
entered_string = gets | |
puts check_balanced_parentheses?(entered_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment