Check Balanced Brackets
JavaScript
Medium
3 views
Problem Description
Given a string with brackets (), {}, [], check if it is balanced. Print YES or NO.
Input Format
One line string.
Constraints
Length up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();const st=[];const pair={')':'(',']':'[','}':'{'};let ok=true;for(const ch of s){if(ch==='('||ch==='['||ch==='{')st.push(ch);else if(ch===')'||ch===']'||ch==='}'){if(st.pop()!==pair[ch]){ok=false;break;}}}if(st.length)ok=false;process.stdout.write(ok?'YES':'NO');
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!