C# Sharp Exercises: Remove duplicate characters from a given string
C# Sharp String: Exercise-46 with Solution
Write a C# Sharp program to remove duplicate characters from a given string.
Sample Solution:-
C# Sharp Code:
using System;
using System.Collections.Generic;
namespace exercises
{
class Program
{
static void Main(string[] args)
{
String str1;
str1="aaaaaabbbbccc";
Console.WriteLine("Original String: "+str1);
Console.WriteLine("After removing duplicates characters from the said string:");
Console.WriteLine(remove_duplicate_chars(str1));
str1="Python";
Console.WriteLine("Original String: "+str1);
Console.WriteLine("After removing duplicates characters from the said string:");
Console.WriteLine(remove_duplicate_chars(str1));
str1="Java";
Console.WriteLine("Original String: "+str1);
Console.WriteLine("After removing duplicates characters from the said string:");
Console.WriteLine(remove_duplicate_chars(str1));
}
public static string remove_duplicate_chars(string str1)
{
var indexes = new Dictionary<char, int>();
for (int i = 0; i < str1.Length; i++)
indexes[str1[i]] = i;
var flag = new HashSet<char>();
var stack = new Stack<char>();
for (int i = 0; i < str1.Length; i++)
{
var ele = str1[i];
if (!flag.Contains(ele))
{
while (stack.Count > 0 && stack.Peek() > ele && i < indexes[stack.Peek()])
flag.Remove(stack.Pop());
flag.Add(ele);
stack.Push(ele);
}
}
var s = new char[stack.Count];
int index = stack.Count - 1;
foreach (var ele in stack)
s[index--] = ele;
return new string(s);
}
}
}
Sample Output:
Original String: aaaaaabbbbccc After removing duplicates characters from the said string: abc Original String: Python After removing duplicates characters from the said string: Python Original String: Java After removing duplicates characters from the said string: Jav
Flowchart :
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to reverse a given string in uppercase.
Next: Write a C# Sharp program to find the length of the longest substring without repeating characters from a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework