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.
1import java.util.Stack;
2
3public class Solution {
4 public String removeDuplicates(String s, int k) {
5 Stack<int[]> count = new Stack<>();
6 StringBuilder sb = new StringBuilder();
7 for (char ch : s.toCharArray()) {
8 if (!sb.isEmpty() && sb.charAt(sb.length() - 1) == ch) {
9 count.peek()[0]++;
10 } else {
11 sb.append(ch);
12 count.push(new int[]{1});
13 }
14 if (count.peek()[0] == k) {
15 sb.delete(sb.length() - k, sb.length());
16 count.pop();
17 }
18 }
19 return sb.toString();
20 }
21}
22
23class Main {
24 public static void main(String[] args) {
25 Solution solution = new Solution();
26 System.out.println(solution.removeDuplicates("deeedbbcccbdaa", 3)); // Output: aa
27 }
28}
29
In this Java solution, a Stack
is used to keep track of the consecutive count of characters. The StringBuilder is used to append characters and simulate stack functionality. When the count reaches k
, the characters are deleted from the StringBuilder.
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)
1using System.Text;
public class Solution {
public string RemoveDuplicates(string s, int k) {
char[] stack = s.ToCharArray();
int[] count = new int[s.Length];
int j = 0;
for (int i = 0; i < s.Length; i++, j++) {
stack[j] = stack[i];
count[j] = (j > 0 && stack[j] == stack[j - 1]) ? count[j - 1] + 1 : 1;
if (count[j] == k) {
j -= k;
}
}
return new string(stack, 0, j);
}
public static void Main(string[] args) {
var solution = new Solution();
Console.WriteLine(solution.RemoveDuplicates("deeedbbcccbdaa", 3));
}
}
This C# solution leverages array modifications and counts to manage and remove sequences of duplicates in-place, allowing us to handle the string without extra space for additional structures.