Skip to content

Instantly share code, notes, and snippets.

@israelalagbe
Created December 13, 2022 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israelalagbe/9337f894f422d2c1bb9a90a55c581ceb to your computer and use it in GitHub Desktop.
Save israelalagbe/9337f894f422d2c1bb9a90a55c581ceb to your computer and use it in GitHub Desktop.
Bracket Matching (find out if all the brackets in a string matches)
/**
* Write 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";
}
// code goes here
return `1 ${bracketPairs}`;
}
// keep this function call here
console.log(SearchingChallenge(readline()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment