Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid.

The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are not.

    public boolean isValid(String s) {
        if(s == null || s.length() == 0){
            return true;
        }
        Stack<Character> stack = new Stack<Character>();
        for(int i= 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == ')'){
                if(stack.empty() || stack.peek() != '('){
                    return false;
                }
                stack.pop();
            } else if(c == ']'){
                if(stack.empty() || stack.peek() != '['){
                    return false;
                }
                stack.pop();
            } else if(c == '}'){
                if(stack.empty() || stack.peek() != '{'){
                    return false;
                }
                stack.pop();
            } else{
                stack.push(c);
            }
        }
        return stack.empty();
    }

results matching ""

    No results matching ""