20. Valid Parentheses (Easy)

https://leetcode.com/problems/valid-parentheses/

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Hints

Solutions

class Solution {
    public boolean isValid(String str) {
        if (str == null) return true;

        Map<Character, Character> map = new HashMap<>();

        map.put(')', '(');
        map.put('}', '{');
        map.put('>', '<');
        map.put(']', '[');

        Stack<Character> stack = new Stack<>();
        for (int i = 0, l = str.length(); i < l; i++) {
            switch (str.charAt(i)) {
                case '(':
                case '{':
                case '[':
                case '<':
                    stack.push(str.charAt(i));
                    break;

                case ')':
                case '}':
                case ']':
                case '>':
                    if (stack.isEmpty()) return false;
                    char top = stack.pop();
                    if (top != map.get(str.charAt(i))) return false;
                    break;

                default: //ignore
            }
        }
        return stack.isEmpty() ? true : false;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-04 12:11:07

results matching ""

    No results matching ""