Created
December 9, 2022 12:02
-
-
Save tluyben/e4c70398b5c2f78d4d2ff32199c29ca2 to your computer and use it in GitHub Desktop.
match curly brackets
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
function getBrackets(str) { | |
// Initialize the stack to keep track of open braces | |
const stack = []; | |
// Initialize the result string | |
let result = ""; | |
// Iterate over each character in the input string | |
for (let i = 0; i < str.length; i++) { | |
const char = str[i]; | |
// If the character is an open brace, push it to the stack | |
if (char === "{") { | |
stack.push(i); | |
} | |
// If the character is a close brace, pop the last open brace from the stack | |
// and extract the substring between the open and close braces | |
if (char === "}") { | |
const start = stack.pop(); | |
result = str.substring(start, i + 1); | |
} | |
} | |
// Return the result string | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment