7ms Java solution with List, beating 98%.


  • 0
    M
    public class Solution {
        public boolean isValid(String s) {
            char[] c = s.toCharArray();
            if(s.length() == 0 || s.length()%2 == 1 || c[0] == ')' || c[0] == ']' || c[0] == '}') return false;
            List<Character> list = new ArrayList<Character>();
            for(int i=0; i<s.length(); i++){
                if(c[i] == '(' || c[i] == '[' || c[i] == '{')     list.add(c[i]);
                else if(c[i] == ')'){
                    if(list.get(list.size()-1) == '(')  list.remove(list.size()-1);
                    else return false;
                } else if(c[i] == ']'){
                    if(list.get(list.size()-1) == '[')  list.remove(list.size()-1);
                    else return false;
                } else if(c[i] == '}'){
                    if(list.get(list.size()-1) == '{')  list.remove(list.size()-1);
                    else return false;
                }
            }
            if(list.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.