Introduction
Given a string which may contains lowercase and uppercase chracters. The task is to remove all duplicate characters from the string and print the resultant string.
Approach
We can use a constant memory space for each of the characters and use it for tracking. The below example covers for alphanumerics. The `chars` array used will be set and used to skip duplicate entries.
using System;
using System.Text;
public class GFG {
static public void Main () {
var count = int.Parse(Console.ReadLine());
for (var i = 0; i < count; i++) {
var input = Console.ReadLine();
Console.WriteLine(RemoveDuplicates(input));
}
}
private static string RemoveDuplicates(string input) {
if (string.IsNullOrEmpty(input) || input.Length == 1) {
return input;
}
var output = new StringBuilder();
// Cover Alphanumerics
int[] chars = new int[200];
foreach (var ch in input) {
var chIndex = (int)(ch);
if (chars[chIndex] == 1) {
continue;
}
output.Append(ch.ToString());
chars[chIndex] = 1;
}
return output.ToString();
}
}