我有一个字符串列表(代表路径和),它们都应该有一个共同的开头(根路径)。我需要有一个共同的开始。
这只是需要组合在一起的几行代码,但我有一种挥之不去的感觉,每年必须将其组合在一起一百万次,并且框架中可能有一个算法可以用于此目的,但找不到任何东西。
另外,我想这个问题之前已经被问过,但我没有回答。
有什么提示吗?
如果有人感兴趣,这就是我想出的:
public static string GetCommonStartingSubString(IList<string> strings)
{
if (strings.Count == 0)
return "";
if (strings.Count == 1)
return strings[0];
int charIdx = 0;
while (IsCommonChar(strings, charIdx))
++charIdx;
return strings[0].Substring(0, charIdx);
}
private static bool IsCommonChar(IList<string> strings, int charIdx)
{
if(strings[0].Length <= charIdx)
return false;
for (int strIdx = 1; strIdx < strings.Count; ++strIdx)
if (strings[strIdx].Length <= charIdx
|| strings[strIdx][charIdx] != strings[0][charIdx])
return false;
return true;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)