All files / leetCode 0020.ts

100% Statements 13/13
100% Branches 8/8
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  6x 1x   5x           5x   5x 17x   17x 8x 2x   6x   9x       3x    
export default function isValid(s: string): boolean {
  if (s.length % 2 === 1)
    return false
 
  const pairs = new Map([
    [')', '('],
    [']', '['],
    ['}', '{'],
  ])
 
  const tokens = []
 
  for (let i = 0; i < s.length; i++) {
    const ch = s[i]
 
    if (pairs.has(ch)) {
      if (tokens.length === 0 || tokens[tokens.length - 1] !== pairs.get(ch))
        return false
 
      tokens.pop()
    } else {
      tokens.push(ch)
    }
  }
 
  return tokens.length === 0
}