Write a C# Sharp program to remove duplicate characters from a given string

  • برمجة سي شارب
  • برمجة

Write a C# Sharp program to remove duplicate characters from a given string.

Expected 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

الأجوبة

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);
        }
  }
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...