Last active
December 8, 2022 11:20
-
-
Save NdauwaRafael/81db83212c8ef66304ba05491d526cda to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A bracket is considered to be any one of the following characters: ‘(‘ and ‘)’ | |
Given a string of brackets, determine whether the string is balanced. | |
If a string is balanced, return YES. Otherwise, return NO. | |
A string is considered balanced if for every opening bracket there is a closing bracket | |
in the correct order. | |
*/ | |
/** | |
* Examples of balanced strings | |
* “()” | |
* “(()())” | |
* “(()(()))” | |
* | |
* Examples of unbalanced strings | |
* “)(“ | |
* “((())()” | |
* “())(“ | |
* “))((()” | |
* "())(()()" | |
* "()))()((()" | |
*/ | |
const balancedBrackets = (brackets)=> { | |
let bracketsArray = brackets.split(''); | |
let pairs = []; | |
for (let i = 0; i<bracketsArray.length; i++){ | |
if(bracketsArray[i] === '(') { | |
pairs.push('('); | |
} | |
if(bracketsArray[i] === ')'){ | |
if (pairs.length > 0){ | |
pairs.pop(); | |
} | |
else { | |
return 'NO'; | |
} | |
} | |
} | |
return pairs.length === 0 ? 'YES' : 'NO'; | |
} | |
console.log(balancedBrackets('()))()((()')) // ===> NO | |
console.log(balancedBrackets('(()(()))')) // ===> YES |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment