Skip to content

Commit

Permalink
Try to fixed 9.52 for pezy#31
Browse files Browse the repository at this point in the history
1. simplify @Mooophy's awesome solution to make code clearer.
2. added comment in key positions.
  • Loading branch information
pezy committed Apr 21, 2015
1 parent db52f92 commit 110b36c
Showing 1 changed file with 23 additions and 23 deletions.
46 changes: 23 additions & 23 deletions ch09/ex9_52.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,34 @@
// push a value onto the stack to indicate that a parenthesized expression was replaced.

#include <stack>
using std::stack;

#include <string>
#include <iostream>
using std::string;

using std::string; using std::cout; using std::endl; using std::stack;
#include <iostream>
using std::cout; using std::endl;

int main()
{
string expression{"This is (pezy)."};
bool bSeen = false;
string expr = "This is (Mooophy(awesome)((((wooooooooo))))) and (ocxs) over";
char repl = '#';
stack<char> stk;
for (const auto &s : expression)
{
if (s == '(') { bSeen = true; continue; }
else if (s == ')') bSeen = false;

if (bSeen) stk.push(s);
}

string repstr;
while (!stk.empty())
{
repstr += stk.top();
stk.pop();
int seen = 0;

for ( auto c : expr ) {
stk.push(c);
if ( c == '(' ) ++seen; // open
if ( seen && c == ')' ) { // pop elements down to the stack
while ( stk.top() != '(' ) stk.pop();
stk.pop(); // including the open parenthesis
stk.push(repl); // push a value indicate it was replaced
--seen; // close
}
}

expression.replace(expression.find("(")+1, repstr.size(), repstr);

cout << expression << endl;

return 0;

// Test
string output;
for ( ; !stk.empty(); stk.pop() ) output.insert(output.begin(), stk.top());
cout << output << endl; // "This is # and # over"
}

0 comments on commit 110b36c

Please sign in to comment.