Simple Java solution with hashmap and stack


  • 0
    R
    public class Solution {
        public boolean isValid(String s) {
            List<Character> stack = new LinkedList<Character>();
            Map<Character,Character> map = new HashMap<Character,Character>();
            map.put(')', '(');
            map.put('}','{');
            map.put(']', '[');
            
            for(int i=0;i<s.length();i++){
                char ch = s.charAt(i);
                if(ch=='{' || ch =='(' || ch=='[')
                    stack.add(ch);
                else{
                    if(stack.size()==0)
                        return false;
                    char sh = stack.remove(stack.size()-1);
                    if(map.get(ch)!=sh)
                        return false;
                }
            }
            if(stack.size()>0)
                return false;
            return true;
        }
    }
    

Log in to reply
 

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