Remove Adjacent Repeated Characters (IV) --- Not done yet.

class Solution { public: string deDup(string input) { // write your solution here if (input.empty()) return input; // initialize everything stack<char> s; s.push(input[0]); input.erase(0, 1); int dup = 0; // whether the top element of s has adjacent duplicates for (auto & c: input){ if (c == s.top()) dup++; else{ if (dup > 0) s.pop(); s.push(c); dup = 0; } } if (dup > 0) s.pop(); // get the results into a string stack<char> buffer; while(!s.empty()){ buffer.push(s.top()); s.pop(); } string res = ""; while(!buffer.empty()){ res.push_back(buffer.top()); buffer.pop(); } return res; } };
For now stuck at : when popped from stack, what if the char that "falls down" is the same as the previous one? Need a while loop, but how?

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.