Java code for Valid Parentheses


  • 0
    K
    class Solution {
        public boolean isValid(String s) {
            if (s == null || s.length() == 0 || s.length() % 2 == 1) return false;
            Map<Character, Character> map = new HashMap<>();
            Stack<Character> stack = new Stack<>();
            map.put(']', '[');
            map.put('}', '{');
            map.put(')', '(');
            stack.push(s.charAt(0));
            for (int i = 1; i < s.length(); i++) {
                if ((stack.size()!=0)&&stack.peek() == map.get(s.charAt(i)))
                    stack.pop();
                else
                    stack.push(s.charAt(i));
            }
            return stack.size() == 0 ? true : false;
        }
    }
    

  • 0
    K

    should be " return stack.isEmpty()" is ok


Log in to reply
 

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