Question:
Remove extra parentheses from the string.
e.g.
((a+b))*c => (a+b)*c
(a+b)+c => (a+b)+c
((a+b)/(c+d)) => ((a+b)/(c+d))
(a+(((b-c)))*d) => (a+(b-c)*d) and so on.
I have come up with the following solution:
Approach: I scan through the string and remember (using a map) the index of a opening parenthesis and whether it's extra or not (by default it's extra). If I find a closing parenthesis I check the corresponding opening parenthesis from map and if it's extra then delete both.
void removeExtraParentheses(string& S){
map<int, bool> pmap;
for(int i = 0; i < S.size(); i++){
map<int, bool>::iterator it;
if(S.at(i) == '('){
pmap[i] = true;
}
else if(S.at(i) == ')'){
it = pmap.end();
it--;
if(!(*it).second){
pmap.erase(it);
}
else{
S.erase(S.begin() + i);
S.erase(S.begin() + (*it).first);
pmap.erase(it);
i = i - 2;
}
}
else{
if(!pmap.empty()){
it = pmap.end();
it--;
(*it).second= false;
}
}
}
}
Time complexity: O(n2)
Space: O(n)
I'm not too happy with my solution because I'm using extra storage and doing it in quadratic time.
Could we do this in O(n) time and O(1) space? If not what is the best one can do?
((a + b) + (c + d))
– Sordello(a + b) + c
is the same asa + b + c
, but in the case ofa + (b + c)
, you need the parentheses. Or perhaps his problem is underspecified: on a Windows machine, or on most Unices, in the last case, you don't need the parentheses forint
, but on some exotic machine, you might. – Muriah(a + b) + (c + d)
: the first can clearly be removed. The second can't at least with floating point. In other words,(a + b) + (c + d)
gives the same results asa + b + (c +d)
, but different results than(a + b) + c + d
. – Muriah(a+b)+c
(if that was about special border cases like @JamesKenze is suggesting, he would have mentioned it). As such, I believe he only wants to remove actual double pairs, in which case your plan doesn't work because it removes something from((a + b) + (c + d))
(or((a + b) + (c + d)) * e
if you prefer) – Sordello