Leetcode–Valid Parentheses

The Problem:

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.

Notes:

  1. This is a basic problem using stack.

Java Solution

public class Solution {
    public boolean isValid(String s) {
        if(s.length()==0 || s.length()%2==1) return false; 
        Stack<Character> st = new Stack<Character>();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i)=='{' || s.charAt(i)=='[' || s.charAt(i)=='(')
                st.push(s.charAt(i));
            else if(st.empty())
                return false;
            else if(s.charAt(i)=='}'){
                if(st.peek()!= '{')
                    return false;
                else
                    st.pop();
            }
            else if(s.charAt(i)==']'){
                if(st.peek()!='[')
                    return false;
                else 
                    st.pop();
            }
            else if(s.charAt(i)==')'){
                if(st.peek()!='(')
                    return false;
                else 
                    st.pop();
            }
        }
        return st.empty();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s