Last active
February 26, 2025 01:04
-
-
Save israelalagbe/9337f894f422d2c1bb9a90a55c581ceb to your computer and use it in GitHub Desktop.
Bracket Matching (find out if all the brackets in a string matches)
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 javascript solution Have the function SearchingChallenge(str) take the str parameter being passed and return 1 #ofBrackets if the brackets are correctly matched and each one is accounted for. Otherwise return 0. For example: if str is "(hello [world])(!)", then the output should be 1 3 because all the brackets are matched and there are 3 pairs of brackets, but if str is "((hello [world])" the the output should be 0 because the brackets do not correctly match up. Only "(", ")", "[", and "]" will be used as brackets. If str contains no brackets return 1. | |
**/ | |
function SearchingChallenge(str) { | |
let bracketMaps = { | |
'(': 0, | |
'[': 0 | |
}; | |
let bracketPairs = 0; | |
for(const char of str) { | |
if(char === '(' || char === '[') { | |
bracketMaps[char]++; | |
bracketPairs++; | |
} | |
if(char === ')') { | |
bracketMaps['(']--; | |
} | |
if(char === ']') { | |
bracketMaps['[']--; | |
} | |
} | |
const isMatched = (bracketMaps['('] === 0 || bracketMaps['[']) === 0; | |
if(!isMatched) { | |
return "0"; | |
} | |
if(bracketPairs === 0) { | |
return "1"; | |
} | |
return `1 ${bracketPairs}`; | |
} | |
console.log(SearchingChallenge(readline())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment