Accepted Java solution


  • 1
    W
    public class Solution {
        public boolean isValid(String s) {
            
            if(s == null)return false;
            if(s == "")return false;
            
            Stack st = new Stack();
            char c = '0';
            char now = '0';
            
            for(int i=0; i<s.length(); i++){
                c = s.charAt(i);
                
                switch(c){
                    case '(':
                        st.push(c);
                        break;
                    case '[':
                        st.push(c);
                        break;
                    case '{':
                        st.push(c);
                        break;
                    case ')':
                        now = st.pop(); 
                        if(now != '(')return false; // not matched
                        break;
                    case ']':
                        now = st.pop(); 
                        if(now != '[')return false; // not matched
                        break;
                    case '}':
                        now = st.pop(); 
                        if(now != '{')return false; // not matched
                        break;
                }
            }
            return st.count == 0;
            
        }
        
        class Stack {
        
            Node top = null;
            int count = 0;
            
            public void push(char v){
                Node n = new Node(v);
                n.next = top;
                top = n;
                count++;
            }
            public char pop(){
                if(count==0)return '0';
                char res = top.val;
                top = top.next;
                count--;
                return res;
            }
            
        }
        class Node {
            char val;
            Node next;
            
            public Node(char v){
                this.val = v;
            }
        }
    }

Log in to reply
 

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