Find the first un-repeated character in a string

后端 未结 30 1394
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  囚心锁ツ
    2020-11-27 19:07

    The following code is in C# with complexity of n.

    using System;
    using System.Linq;
    using System.Text;
    
    namespace SomethingDigital
    {
        class FirstNonRepeatingChar
        {
            public static void Main()
            {
                String input = "geeksforgeeksandgeeksquizfor";
                char[] str = input.ToCharArray();
    
                bool[] b = new bool[256];
                String unique1 = "";
                String unique2 = "";
    
                foreach (char ch in str)
                {
                    if (!unique1.Contains(ch))
                    {
                        unique1 = unique1 + ch;
                        unique2 = unique2 + ch;
                    }
                    else
                    {
                        unique2 = unique2.Replace(ch.ToString(), "");
                    }
                }
                if (unique2 != "")
                {
                    Console.WriteLine(unique2[0].ToString());
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("No non repeated string");
                    Console.ReadLine();
                }
            }
        }
    }
    

提交回复
热议问题