Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//Algo
//for every closing type of bracket, there should be opening type of bracket
//No of every type of opening bracket should be equal to no of every type of
//closing bracket
const tripleBracketMatcher = str => {
let storage = [];
let perfect = {
"(": ")",
"[": "]",
"{": "}"
};
for (let i = 0; i < str.length; i++) {
if (str[i] === "(" || str[i] === "[" || str[i] === "{") {
storage.push(str[i]);
} else if (str[i] === ")" || str[i] === "]" || str[i] === "}") {
let lastBracket = storage.pop();
if (str[i] !== perfect[lastBracket]) {
return false;
}
}
}
if (storage.length !== 0) {
return false;
}
return true;
};
//Test Cases:
const testCases = [
{
input: "asdfs(sdfd[dfdsf]sdfd{dsfdsfsd})",
output: true
},
{
input: "asdfs(sdfd[dfdsf]sdfd{dsfdsfsd})",
output: true
},
{
input: "hello world",
output: true
},
{
input: "asdfs(sdfd[dfdsf]sdfd{dsfdsfsd}[)",
output: false
},
{
input: "s({h){il(pi",
output: false
},
{
input: "shi{lpi}",
output: true
},
{
input: "sh[ilpi",
output: false
},
{
input: "asd()][{}",
output: false
},
{
input: "a({s)[]}d",
output: false
}
];
testCases.forEach(({ input, output }, index) => {
console.log(
`Test case ${index} (${input}): ${
tripleBracketMatcher(input) === output ? "successs" : "failure"
}`
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment