Recursively remove all adjacent duplicates

Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples.
Input: azxxzy
Output: ay
First "azxxzy" is reduced to "azzy". The string "azzy" contains duplicates,
so it is further reduced to "ay".

Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to "gksforgg". The string "gksforgg" contains
duplicates, so it is further reduced to "gksfor".

Input: caaabbbaacdddd
Output: Empty String

Input: acaaabbbacdddd
Output: acac

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "acaaabbbacdddd";
            while (!RepetitionCheck(str, out str)) ;
            Console.WriteLine(str);
        }

        public static bool RepetitionCheck(string str, out string str1)
        {
            str1 = str;
            for (int i = 0; i < str.Length - 1; i++)
            {
                int count = 0;
                while (str.Substring(i, 1) == str.Substring(i + 1, 1))
                {
                    count++; i++;
                    if (i == str.Length - 1)
                        break;
                }
                if(count != 0)
                {
                    str1 = str.Remove(i - count, count + 1);
                    return false;
                }
            }
            return true;
        }
    }
}

Output
=======
acac
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s