Valid Parentheses (Easy)

99 阅读1分钟

Algorithm

Given a string s 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.
  3. Every close bracket has a corresponding open bracket of the same type.

 

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.
class Solution {

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

    static {
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        map.put('?', '?');
    }

    public boolean isValid(String s) {
        // Because the constraints limit s.length > 1, so we don't hava to check the length. 
        // if (s.length() > 0 &&  !map.containsKey(s.charAt(0))) {
        //     return false;
        // }

        // Easily, we can consider using a stack to store open bracket, when the next character can compostition bracket, pop top character of stack.
        LinkedList<Character> stack = new LinkedList<>(); 
        // why we push '?' to stack ,that bacase when the stack is empty ,use function pop() will NullPointexception. 
        // (chinglish, so what? enough for everyone to understand :) )
        stack.push('?');
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (map.containsKey(ch)) {
                stack.push(ch);
            } else if (map.get(stack.pop()) != ch) {
                return false;
            }
        }
        return stack.size() == 1;
    }
}

Summary of basic knowledge

  • the class of LinkedList
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

We can free use it for a stack or queue.

  • As a stack we can use the pop() & addFirst() and push() & removeFirst() funtions.
  • As a queue we can use the offer() & addFirst() and poll() & removeLast() funtions.

Vocabulary

  • bracket, parentheses
  • determine
  • correct
  • corresponding
  • constrains
  • consists
  • stack, queue, deque