Code Lab

Mode entretien. Minuteur de 15 min, sans indices ni autocomplétion

Balanced brackets

DifficileStrings15 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.

Exemples

isBalanced('([]{})')

Renvoie true

isBalanced('([)]')

Renvoie false

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

Renvoie true

Posé chez Swiggy · Source

Chargement de l'éditeur...
  1. EntréeisBalanced('([]{})')
    Attendutrue
  2. EntréeisBalanced('([)]')
    Attendufalse
  3. EntréeisBalanced('if (a[0]) { b() }')
    Attendutrue

Les tests cachés se lancent à la soumission