我只想從字串串列中獲取最小的唯一子序列。例如:
- [1,11,111,12,13] - 我只想得到第一個值,即 1
- [11,12,13,131,141,14,111] - 我想要值 - 僅 11,12,13,14。
我正在嘗試但面臨獲取確切值的問題。Values是元素的集合。
var str = new List<string>();
string[] str1 = values.OrderBy(x => x.Length).ToArray();
foreach(var s in str1)
{
if (str.count() < 1)
str.Add(s);
else
{
int count = str.Count;
for (int i=0; i < count; i )
{
if (s.StartsWith(str[i]))
{
break;
}
str.Add(s);
}
}
}
任何幫助,將不勝感激。謝謝!
uj5u.com熱心網友回復:
你快到了。但是您s在檢查集合中已經包含的所有元素之前添加。并且實際上并不需要檢查“仍然為空的結果”。
如果您可以使用 Linq,則以下內容應該有效。看代碼說明
public static List<string> prefixFree(List<string> words) {
//order the words by their length
var w = words.OrderBy(x => x.Length);
var result = new List<string>();
//for each of the words check
foreach (var s in w) {
//if it starts with any of the words already in the result
if (!result.Any(x => s.StartsWith((x))))
//if no match is found, add it to the result
result.Add(s);
}
return result;
}
uj5u.com熱心網友回復:
根據需要嘗試/改進...
//ints
var ints = new List<int> { 1, 2, 3, 4, 7, 8, 7, 3, 9 };
//strings
var strs = new List<string> { "foo", "bar", "baz", "lorem", "1", "2", "baz", "7", "1", "8", "9", "1" };
//ints
GetUniques<int>(ints);
//strings
GetUniques<string>(strs);
void GetUniques<T>(IEnumerable<T> e)
{
//if count > 1 then it has 1 or more duplicates...
var group = e.GroupBy(g => g).Where(g => g.Count() == 1);
foreach (var g in group)
{
Console.WriteLine(g.Key);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337223.html
