Created
October 25, 2019 05:11
-
-
Save joegiralt/fad47aed2eb0b33d0d1cb86a147124a2 to your computer and use it in GitHub Desktop.
interview prep 1.
This file contains hidden or 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
// I like parentheticals (a lot). | |
// "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing." | |
// Write a function that, given a sentence like the one above, along with the position of an opening parenthesis, finds the corresponding closing parenthesis. | |
// Example: if the example string above is input with the number 10 (position of the first parenthesis), the output should be 79 (position of the last parenthesis). | |
const findParenPosition = (string, pos) => { | |
let openStack = [pos]; | |
let closeStack = []; | |
let scanPosition = pos + 1; | |
while (openStack.length !== 0) { | |
if (string[scanPosition] === '(') { | |
openStack.push(scanPosition) | |
} else if (string[scanPosition] === ')') { | |
closeStack.push(scanPosition) | |
}; | |
if (closeStack.length === 1 && openStack.length === 1) { | |
break; | |
} else if (closeStack.length && openStack.length) { | |
openStack.pop(); | |
closeStack.pop(); | |
}; | |
scanPosition++; | |
}; | |
return closeStack[0]; | |
}; | |
const string1 = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."; | |
findParenPosition(string1, 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment