Created
February 26, 2019 14:18
-
-
Save hmenn/4c32063a38b7c82622797eee35ad4545 to your computer and use it in GitHub Desktop.
Interview Cake Weekly Problem #232: Parenthesis Matching
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). | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <map> | |
#include <stack> | |
int find_corresponding_end_paranthesis(std::string text, int open_paranthesis_index){ | |
std::map<int, int> paranthesis; | |
std::stack<int> history; | |
for(int i=open_paranthesis_index; i<text.size();++i){ | |
if(text[i]==')'){ | |
int openIndex = history.top(); | |
history.pop(); | |
paranthesis.emplace(openIndex, i); | |
}else if(text[i]=='('){ | |
history.push(i); | |
} | |
} | |
return paranthesis[open_paranthesis_index]; | |
} | |
int main() { | |
std::string text = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."; | |
std::cout<<find_corresponding_end_paranthesis(text, 10)<<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment