Code Lab

Modo entrevista. Temporizador de 15 min, sin pistas y sin autocompletado

Balanced brackets

DifícilStrings15 min

Write a function isBalanced(text) that returns true when the brackets in the string text are balanced, and false otherwise.

  • There are three kinds of brackets: (), [] and {}. Every other character is skipped: 'if (a[0]) { b() }' is balanced.
  • Every opening bracket needs a closing bracket of the same kind after it: '(]' is not balanced.
  • Brackets close in the reverse order of opening: '([)]' is not balanced, '([])' is.
  • A closing bracket with no open bracket before it makes the text not balanced: ')(' is not balanced.
  • A string with no brackets, also an empty string, is balanced.
  • The text can be long, up to 100 000 characters, and brackets can nest 50 000 levels deep. Your code must finish in time.

Ejemplos

isBalanced('([]{})')

Devuelve true

isBalanced('([)]')

Devuelve false

isBalanced('if (a[0]) { b() }')

Devuelve true

Preguntada en Swiggy · Fuente

Cargando el editor…
  1. EntradaisBalanced('([]{})')
    Esperadotrue
  2. EntradaisBalanced('([)]')
    Esperadofalse
  3. EntradaisBalanced('if (a[0]) { b() }')
    Esperadotrue

Las pruebas ocultas se ejecutan al enviar