Fastest way to implement Duplicate Character Removal in String (C#)

前端 未结 5 693
说谎
说谎 2020-12-14 12:43

In C#, what is the fastest way to detect duplicate characters in a String and remove them (removal including 1st instance of the duplicated character)?

5条回答
  •  渐次进展
    2020-12-14 13:05

    This one should be pretty quick (and it preserves the original order):

    public static string RemoveDuplicates(string source)
    {
        HashSet found = new HashSet();
        HashSet dupes = new HashSet();
    
        foreach (char c in source)
        {
            if (!found.Add(c))
            {
                dupes.Add(c);
            }
        }
    
        StringBuilder sb = new StringBuilder(source.Length);
        foreach (char c in source)
        {
            if (!dupes.Contains(c))
            {
                sb.Append(c);
            }
        }
        return sb.ToString();
    }
    

提交回复
热议问题