How to remove all adjacent duplicate characters from a string until no more can be removed in C#

1 Answer

0 votes
using System;
using System.Text;

class Program
{
    static string RemoveAdjacentDuplicates(string s) {
        var stack = new StringBuilder();

        foreach (char ch in s) {
            int n = stack.Length;

            if (n > 0 && stack[n - 1] == ch) {
                stack.Remove(n - 1, 1);   // pop
            }
            else {
                stack.Append(ch);        // push
            }
        }

        return stack.ToString();
    }

    static void Main()
    {
        string s = "abbacccada";
        
        Console.WriteLine(RemoveAdjacentDuplicates(s));  
    }
}



/*
run:

cada

*/

 



answered Mar 7 by avibootz

Related questions

...