1. 程式人生 > >在一個字串陣列中找出重複的字串(C#)

在一個字串陣列中找出重複的字串(C#)

方法一:(hashtable)推薦使用
private bool checkImportDuplicate(string[] str )
{
bool flag = false;
Hashtable hash = new Hashtable();
for (int i = 0; i < str.Length; i++)
{
if (!hash.ContainsKey(str[i]))
{
hash.Add(str[i], i);
cntIntLists[i].Add(i);//全域性變數List[] cntIntLists = new List[N];記錄重複的字串的下標值
}
else
{
int value = (int)hash[str[i]];
cntIntLists[value].Add(i);
flag = true;
}
}
return flag;
}
方法二:(雙重迴圈)
private bool checkImportDuplicate(string[] str )
{
bool flag = false;
bool[] f=new bool[str.Length];
for (int i = 0; i < str.Length; i++)
{
f[i] = true;
}
List[] cnt=new List[];
for (int i = 0; i < str.Length-1&&f[i]; i++)
{
cntIntLists[i].Add(i);//全域性變數List[] cntIntLists = new List[N];記錄重複的字串的下標值
for (int j = i + 1; j < str.Length&&f[j]; j++)
{
if (str[i].Equals(str[j]))
{
cntIntLists[i].Add(j);
flag = true;
f[i] = false;
}
}
}
return flag;
}