I found a piece of code over leetcode and I compared the same to my solution.
Problem link: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii
Leetcode solution: (16 ms & 10.2 MB)
string removeDuplicates1(string s, int k) {
vector<pair<char, short>> st;
string res;
for (auto ch : s) {
if (st.empty() || st.back().first != ch) st.push_back({ ch, 0 });
if (++st.back().second == k) st.pop_back();
}
for (auto& p : st) res += string(p.second, p.first);
return res;
}
My solution: (32 ms & 132.5 MB)
string removeDuplicates2(string str, int k) {
if(k == 1)
return "";
vector<pair<char, short>> S;
for(int i=0; i<str.size(); i++) {
if(!S.empty() && S.back().first == str[i])
S.back().second++;
else
S.push_back({str[i], 1});
if(S.back().second == k)
S.pop_back();
}
string result = "";
for(auto& i : S) {
result = result + string(i.second, i.first);
}
return result;
}
Why removeDuplicates1 is faster and memory efficient than removeDuplicates2?
