How can you remove duplicate characters in a string?

前端 未结 20 2299
离开以前
离开以前 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:08

    For arbitrary length strings of byte-sized characters (not for wide characters or other encodings), I would use a lookup table, one bit per character (32 bytes for a 256-bit table). Loop through your string, only output characters that don't have their bits turned on, then turn the bit on for that character.

    string removedupes(string s)
    {
        string t;
        byte[] found = new byte[256];
        foreach(char c in s)
        {
            if(!found[c]) {
                t.Append(c);
                found[c]=1;
            }
        }
        return t;
    }
    

    I am not good with C#, so I don't know the right way to use a bitfield instead of a byte array.

    If you know that your strings are going to be very short, then other approaches would offer better memory usage and/or speed.

提交回复
热议问题