我有一个包含文件和目录的列表 List<string> pathes
。现在我想计算每个路径共享的最深公共分支。
我们可以假设它们都有一个共同的路径,但一开始不知道这个路径是什么。
假设我有以下三个条目:
- C:/Hello/World/This/Is/An/Example/Bla.cs
- C:/Hello/World/This/Is/Not/An/Example/
- C:/Hello/Earth/Bla/Bla/Bla
这应该得到结果:C:/Hello/ ,因为 Earth 打破了这个子目录 "链"。
第二个例子:
- C:/Hello/World/This/Is/An/Example/Bla.cs
- C:/Hello/World/This/Is/Not/An/Example/
-> C:/Hello/World/This/Is/
你会如何处理?我尝试使用 string.split(@"/") 并从第一个字符串开始检查该数组的每个部分是否包含在其他字符串中。然而,这将是一个非常昂贵的调用,因为我正在遍历 (list_of_entries)^list_of_entries。是否有更好的解决方案可用?
我当前的尝试类似于以下内容(C# + LINQ):
public string CalculateCommonPath(IEnumerable<string> paths)
{
int minSlash = int.MaxValue;
string minPath = null;
foreach (var path in paths)
{
int splits = path.Split('\\').Count();
if (minSlash > splits)
{
minSlash = splits;
minPath = path;
}
}
if (minPath != null)
{
string[] splits = minPath.Split('\\');
for (int i = 0; i < minSlash; i++)
{
if (paths.Any(x => !x.StartsWith(splits[i])))
{
return i >= 0 ? splits.Take(i).ToString() : "";
}
}
}
return minPath;
}