我通過一個算法問題集這對以下問題的工作:確定是否字符串具有獨特的所有字符
「確定一個字符串擁有所有獨特字符假設你只能使用數組。」。
我有一個工作解決方案,但我想看看是否有任何更好的時間複雜度方面的優化。我不想使用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