Sponsored
Sponsored
This approach utilizes a stack data structure to track characters and their counts. As we iterate through the string, we push characters with their current counts on the stack. When the count of the top character in the stack reaches k
, we pop the character from the stack to simulate removal of duplicates.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack and auxiliary storage.
1#include <iostream>
2#include <string>
3#include <vector>
4
5std::string removeDuplicates(const std::string& s, int k) {
6 std::string result;
7 std::vector<int> count;
8 for (char ch : s) {
9 if (!result.empty() && result.back() == ch) {
10 count.back()++;
11 } else {
12 result.push_back(ch);
13 count.push_back(1);
14 }
15 if (count.back() == k) {
16 result.erase(result.size() - k);
17 count.pop_back();
18 }
19 }
20 return result;
21}
22
23int main() {
24 std::string s = "deeedbbcccbdaa";
25 int k = 3;
26 std::cout << removeDuplicates(s, k) << std::endl;
27 return 0;
28}
29
This C++ solution uses a vector to simulate the stack, where each character in the resulting string is paired with its count. When we hit k
consecutive characters, they are removed from the string.
This approach utilizes a two-pointer technique to modify the string in place. Here, we treat the string as a character array, using one pointer to scan the input and another to build the output string. A helper array is used to store counts of consecutive characters.
Time Complexity: O(n)
Space Complexity: O(n)
1
The C solution employs an extra integer array to keep track of the count of consecutive characters for each position j
in the resultant array. Characters are removed in-place by adjusting the index j
accordingly.