remove duplicate adjacent characters

By   Tewodros   Date Posted: Oct. 31, 2023  Hits: 437   Category:  Algorithm   Total Comment: 0             A+ A-


side

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);

   }

 

   

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* aunrgt

Back to Top