[Solution][20. Valid Parentheses]


  • 0
    H
    1. Create Hashtable to match between '(' , ')' and '[', ']'
    2. We using stack to push '(', '[', '{'
    3. For each character and compare with what we have got in stack
    public boolean isValid(String s) {
            Hashtable<Character, Character> compareHash = new Hashtable<Character, Character>();
    		compareHash.put('(', ')');
    		compareHash.put('[', ']');
    		compareHash.put('{', '}');
            char[] arrayChar = s.toCharArray();
            String openSyntax = "({[";
            String closeSyntax = ")}]"; 
            Stack st = new Stack();
            for(int i = 0; i < arrayChar.length; i++){
                if(openSyntax.indexOf(arrayChar[i])>=0){
                    st.push(arrayChar[i]);
                }else{
                    if(st.size() == 0) return false;
                    if(arrayChar[i] != compareHash.get((char) st.pop())){
                        return false;
                    }
                }
            }
            if(st.size() == 0){
                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.