JavaScript bootcamp · Lab 49

Matching brackets

mediumArrays15 minLesson: Arrays

Read the question, write JavaScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a string of ()[]{}. Print yes if brackets match, else no.

Input. One string.

Output. yes or no.

Examples

Example 1
Input
([])
Output
yes
Example 2
Input
([)]
Output
no
Hint
  1. Stack: push openers; pop on closers.
Show correct code

Peek only after you have tried. You can still Check your own version.

const s = readLine().trim();
const pair = { ')': '(', ']': '[', '}': '{' };
const st = [];
let ok = true;
for (const ch of s) {
  if ('([{'.includes(ch)) st.push(ch);
  else if (')]}'.includes(ch)) {
    if (st.pop() !== pair[ch]) { ok = false; break; }
  }
}
console.log(ok && st.length === 0 ? 'yes' : 'no');
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.