How can you remove duplicate characters in a string?

前端 未结 20 2256
离开以前
离开以前 2020-12-05 16:39

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.

So an an example is if I pass string str = \"

20条回答
  •  伪装坚强ぢ
    2020-12-05 17:12

    //this is in C#, validation left out for brevity //primitive solution for removing duplicate chars from a given string

        public static char[] RemoveDup(string s)
        {
            char[] c = new char[s.Length];
            int unique = 0;
            c[unique] = s[0];  // Assume: First char is trivial
            for (int i = 1; i < s.Length; i++)
            {
                if (s[i-1] != s[i]
            c[++unique] = s[i];
            }
            return c;
        }
    

提交回复
热议问题