remove duplicate adjacent characters
Example
absaasbb
output:
a
Solution:
We can use two pointers approach in this case. We need to create a result array and copy non repeating character to this array. When we check if adjacent chars are duplicate we need to do it one char from the input string and the other char from the result array.
static string RemoveAdjacentDuplicates(string input)
{
if (string.IsNullOrEmpty(input))
return input;
char[] result = new char[input.Length];
int index = 0;
for (int i = 0; i < input.Length; i++)
{
if (index > 0 && result[index - 1] == input[i])
{
// Remove the duplicate character
index--;
}
else
{
// Add the character to the result
result[index] = input[i];
index++;
}
}
return new string(result, 0, index);
}