Solution 1Stack Match

  • TimeO(n)
  • SpaceO(n)

where, n is the length of s.
NOTE: Using hashmap like a switch, makes it quicker instead of multiple if-else conditions.

class Solution:
    '''
    Time Complexity: O(n)
    Space Complexity: O(n)
    where, n is the length of s.
    NOTE: Using hashmap like a switch, makes it quicker instead of multiple if-else conditions.
    '''
    def isValid(self, s: str) -> bool:
        openedBras = []
        bras =  {
                ')':'(',
                ']':'[',
                '}':'{'
                }
        for bra in s:
            if bra in bras:
                if not openedBras or openedBras.pop() != bras[bra]:
                    return False
            else:
                openedBras.append(bra)
        return False if openedBras else True
Leet Code/python.py · L669–690
public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    String par = "{([";
    for (char c: s.toCharArray()) {
        if (par.indexOf(c) != -1) {
            stack.push(c);
        } else {
            switch(c) {                
                case '}':
                    if (stack.isEmpty() || stack.pop() != '{') return false;
                    break;
                case ']':
                    if (stack.isEmpty() || stack.pop() != '[') return false;
                    break;
                case ')':
                    if (stack.isEmpty() || stack.pop() != '(') return false;
                    break;
            }
        }
    }
    return stack.isEmpty();
}
Leet Code/java.java · L591–613