我必须实现一个函数,它接受一个字符串作为输入,并从该字符串中找到非重复的字符.
所以一个例子是如果我传递字符串str ="DHCD"它将返回"DHC"或str2 ="KLKLHHMO"它将返回"KLHMO"
CMS*_*CMS 32
Linq方法:
public static string RemoveDuplicates(string input)
{
return new string(input.ToCharArray().Distinct().ToArray());
}
Run Code Online (Sandbox Code Playgroud)
它会完成这项工作
string removedupes(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach(char c in s)
{
if(found.Contains(c))
continue;
newString+=c.ToString();
found.Add(c);
}
return newString;
}
Run Code Online (Sandbox Code Playgroud)
我应该注意到这是犯罪效率低下的.
我想我在第一次修订时很神志不清.
对于任意长度的字节大小的字符串(不适用于宽字符或其他编码),我会使用一个查找表,每个字符一位(256位表为32位).循环遍历字符串,只输出没有打开位的字符,然后打开该字符的位.
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;
}
Run Code Online (Sandbox Code Playgroud)
我对C#不好,所以我不知道使用位域而不是字节数组的正确方法.
如果您知道您的字符串将非常短,那么其他方法将提供更好的内存使用和/或速度.
归档时间: |
|
查看次数: |
53615 次 |
最近记录: |