Stack

Valid Parentheses

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

Code:

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');
        Stack<Character> stack = new Stack<>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                char topChar = stack.isEmpty() ? '#' : stack.pop();
                if (topChar != map.get(c)) return false;
            } else {
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }
}
  • Stack is FILO (First In Last Out);

  • Stack methods: push(), pop(), isEmpty();

  • HashMap methods: containsKey(), get(), put();

  • Time complexity: O(n);

Simplify Path

Link: https://leetcode.com/problems/simplify-path/

Code:

  • Stack can not pop when it is empty;

  • Java stack method push() vs. add(): see stackoverflow;

  • split() method for String;

  • equals() method for String;

Last updated