Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active November 1, 2020 10:00
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 ShilpiMaurya/e2add694077cecc2f8318a33611d8ae1 to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/e2add694077cecc2f8318a33611d8ae1 to your computer and use it in GitHub Desktop.
//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