Java solution


  • 0
    M

    class Solution {
    public boolean isValid(String s) {

        Stack st = new Stack();
        
        for(int i=0; i < s.length(); i++)
        {
            if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
            {
                st.push(new Character(s.charAt(i)));
            }
            else
            {
                if(s.charAt(i) == ')')
                {
                    while(!st.empty() && (Character)st.peek() != '(' && (Character)st.peek() != '[' && (Character)st.peek() != '{')
                        st.pop();
                    
                    if(st.empty())
                        return false;
                    else if((Character)st.peek() == '(')
                        st.pop();
                    else
                        return false;
                    
                }
                
                else if(s.charAt(i) == ']')
                {
                    while(!st.empty() && (Character)st.peek() != '(' && (Character)st.peek() != '[' && (Character)st.peek() != '{')
                        st.pop();
                    
                    
                    if(st.empty())
                        return false;
                    else if((Character)st.peek() == '[')
                        st.pop();
                    else
                        return false;
                    
                        
                }
                
                else if(s.charAt(i) == '}')
                {
                    while(!st.empty() && (Character)st.peek() != '(' && (Character)st.peek() != '[' && (Character)st.peek() != '{')
                        st.pop();
                    
                    if(st.empty())
                        return false;
                    else if((Character)st.peek() == '{')
                        st.pop();
                    else
                        return false;
                    
                }
            }
            
        }
        
        if(st.empty())
            return true;
        else
            return false;
    }
    

    }


Log in to reply
 

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