Skip to content

Instantly share code, notes, and snippets.

@coxato
Created October 30, 2021 02:59
Show Gist options
  • Save coxato/f7aa5d4173452c870062c1bd74c2a410 to your computer and use it in GitHub Desktop.
Save coxato/f7aa5d4173452c870062c1bd74c2a410 to your computer and use it in GitHub Desktop.
proper nesting
// Carlos Martinez @coxato
// the problem is about validate and fill a string with square brackets, curly brackets and braces () [] {}
// if you have for example
// "]-(" you have to return "[]-()"
// "[{{" returns "[{{}}]"
// "" returns ""
// "} { [()] (()v()) } ])" returns "([{} { [()] (()v()) } ])"
// "(]" returns null
// "[}}[" returns null
const openChar = {
'{': '}',
'[': ']',
'(': ')'
}
const closeChar = {
'}': '{',
']': '[',
')': '('
}
// save here the completed string, if we need to complete of course
let completedString;
function validateAndComplete(str) {
// stack for save the {[( characters
let openStack = [];
for (let i = 0; i < str.length; i++) {
let char = str[i];
if(openChar[char]){
openStack.push(char);
}
else if(closeChar[char]){
const lastOpenChar = openStack.pop();
if(lastOpenChar){
if(openChar[lastOpenChar] !== char) return false;
}
// if it's undefined, check if we can complete the string
// this also means that we have a ), ] or } that can be added at the beginning of the string
else {
completedString = closeChar[char] + str;
return validateAndComplete(completedString);
}
}
}
// if some (, [ or { is still inside the stack means
// that we can take it and add the corresponding ), ] or } at end of string
if(openStack.length){
completedString = str + openChar[openStack.pop()];
return validateAndComplete(completedString);
}
return true;
}
function nest(str) {
completedString = ''; // reset
if(validateAndComplete(str)){
return completedString || str;
};
return null;
}
// some test cases
// const testCases = [
// "( )[ ]",
// "]-(",
// "}(", // I dunno why should be null, I think {}()
// "([{}{}]())",
// "",
// "([hi]) { hello [] (nice) {123} }",
// "[}}[",
// ")()] {[]} (",
// "[{{",
// "{ [] (}",
// "(]",
// "} { [()] (()v()) } ])"
// ];
// testCases.forEach( t => {
// console.log(t, '->', nest(t));
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment