Java Stack Solution


  • 0
    D
    class Solution
    {
        public boolean isValid(String s)
        {
        	Stack<String> stack = new Stack<String>();
        	for(int i=0; i<s.length(); i++)
            {
                try
                {
                    switch(s.charAt(i))
                    {
                	    case '(':
                		    stack.push("(");
                		    break;
                	    case ')':
                		    if(stack.peek()=="(")
                		    {
                			    stack.pop();
                		    }
                		    else
                		    {
                			    return false;
                		    }
                		    break;
                	    case '[':
                		    stack.push("[");
                		    break;
                	    case ']':
                		    if(stack.peek()=="[")
                		    {
                			    stack.pop();
                		    }
                		    else
                		    {
                			    return false;
                		    }
                		    break;
                	    case '{':
                		    stack.push("{");
                		    break;
                	    case '}':
                		    if(stack.peek()=="{")
                		    {
                			    stack.pop();
                		    }
                		    else
                		    {
                			    return false;
                		    }
                		    break;
                	    default:
                		    return false;
                    }
                }
                catch(Exception e)
                {
                    return false;
                }
            }
            
            return (stack.isEmpty());
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.