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
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();
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With