-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompress.cpp
More file actions
42 lines (34 loc) · 1010 Bytes
/
compress.cpp
File metadata and controls
42 lines (34 loc) · 1010 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
string compressWord(const string& word, int k) {
stack<pair<char, int>> charStack;
for (char ch : word) {
if (charStack.empty() || charStack.top().first != ch) {
charStack.push(make_pair(ch, 1));
} else {
charStack.top().second++;
if (charStack.top().second == k) {
charStack.pop();
}
}
}
string finalWord;
while (!charStack.empty()) {
for (int i = 0; i < charStack.top().second; i++) {
finalWord += charStack.top().first;
}
charStack.pop();
}
reverse(finalWord.begin(), finalWord.end()); // The stack reverses the order
return finalWord;
}
int main() {
string word = "abaa";
int k = 2;
string finalWord = compressWord(word, k);
cout << "Final word after compression: " << finalWord << endl;
return 0;
}