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