Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find even duplicates character in a string in C# .Net

Tags:

string

c#

.net

I have a question of how to remove even duplicates in a string in C#.

example - input string:

acdhqodcqasaf

output:

acdhqosaf

What I really mean is to remove even occurrences of characters.I have written the logic but I have used nested for loops and its efficiency is O(n^2) which is not good efficiency.So I was asked to do in different way searched online still did not get the answer

like image 573
Vadiya Avatar asked Dec 06 '25 22:12

Vadiya


2 Answers

You could use a dictionary to track the number of occurences and use the % operator:

string input = "acdhqodcqasaf";
var charOccurences = new Dictionary<char, int>();
int removeEvery = 2;
var outputBuilder = new StringBuilder();

foreach (char c in input)
{
    charOccurences.TryGetValue(c, out int charOccurence);
    charOccurence++;
    charOccurences[c] = charOccurence;
    if (charOccurence % removeEvery != 0)
        outputBuilder.Append(c);
}

string output = outputBuilder.ToString();
like image 153
Tim Schmelter Avatar answered Dec 08 '25 10:12

Tim Schmelter


I'd use a HashSet to keep track of which characters you've seen an odd number of times.

string input = "acdhqodcqasaf";
var oddOccurrences = new HashSet<char>();
var output = new StringBuilder();
foreach (var c in input)
{
    if (!oddOccurrences.Contains(c))
    {
        output.Append(c);
        oddOccurrences.Add(c);
    }
    else
    {
        oddOccurrences.Remove(c);
    }
}
Console.WriteLine(output.ToString());
like image 24
StriplingWarrior Avatar answered Dec 08 '25 11:12

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!