字符串列表中的最小唯一子序列



我只想从字符串列表中获得最小的唯一子序列。例如:

  1. [1,111,111,12,13] -我只想得到第一个值,即1
  2. [11,12,13,131,141,14,111] -我只想要值- 11,12,13,14。

我正在尝试,但面临的问题,以获得确切的值。元素的集合。

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);
}
}
}

任何帮助都会很感激。谢谢!

你差一点就成功了。但是在检查集合中已经包含的所有元素之前,您添加了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;
}

最新更新