我通过一个算法问题集这对以下问题的工作:确定是否字符串具有独特的所有字符
“确定一个字符串拥有所有独特字符假设你只能使用数组。”。
我有一个工作解决方案,但我想看看是否有任何更好的时间复杂度方面的优化。我不想使用LINQ。感谢您提供的任何帮助!
static void Main(string[] args)
{
FindDupes("crocodile");
}
static string FindDupes(string text)
{
if (text.Length == 0 || text.Length > 256)
{
Console.WriteLine("String is either empty or too long");
}
char[] str = new char[text.Length];
char[] output = new char[text.Length];
int strLength = 0;
int outputLength = 0;
foreach (char value in text)
{
bool dupe = false;
for (int i = 0; i < strLength; i++)
{
if (value == str[i])
{
dupe = true;
break;
}
}
if (!dupe)
{
str[strLength] = value;
strLength++;
output[outputLength] = value;
outputLength++;
}
}
return new string(output, 0, outputLength);
}
这应该是在[codereview.stackexchange.com](http://codereview.stackexchange.com) –
的开销是,你没有嵌套循环 - 通过迭代长度的字符串 - 而不是使用更简单的IndexOf函数。提示:编码时尝试将事物想象成“抽象”。如果我要求你写一个函数来计算每个人在这个线程中的年龄,你会怎么称呼这个方法? 'SumAges(int [] ages)'或 - 从目的中抽象出功能并将其称为'Sum(int [] numbers)'。反之亦然,你会考虑对字符串进行嵌套循环操作,以检查char是否在字符串中,而不是查找内置的BCL字符串方法吗? –
@DaveZych - 嗨戴夫,我不知道codereview.stackexchange.com。在SO和CR上发布问题的协议是什么? – mynameisneo