CLEAN CODE GENERATE ALL PARENTHESES | STACK | LIFO PROBLEMS

By: Saurav

2018-02-07 01:17:00 UTC

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Return 0 / 1 ( 0 for false, 1 for true ) for this problem

InterviewBit

This is one of the most famous problems for illustrating the use of stacks. This problem is about knowing data structure. Knowing why LIFO can solve this problem and then using stacks for implementing the LIFO.

Let's see it in action:

def isValid(a)
        return 1 if a.length < 1
        
        return 0 if a.length < 2
        
        stack = Array.new
        
        (0..a.length-1).each do |i|
            stack << a[i] if a[i] == "(" or a[i] == "{" or a[i] == "["
            
            if a[i] == ")"
                return 0 if stack.pop != "("
            end
            if a[i] == "}"
                return 0 if stack.pop != "{"
            end
            if a[i] == "]"
                return 0 if stack.pop != "["
            end
                
        end
        
        stack.empty? ? 1 : 0
        

    end

Looks good to me.


Let me know what you think!
twitter: sprakash24oct
linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)