您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Longest Common Prefix

2012-09-20 03:42 405 查看
Write a function to find the longest common prefix string amongst an array of strings

public static string LongestCommonPrefix(List<string> strs)
{
if (strs.Count == 0)
return "";
if (strs.Count == 1)
return strs[0];

bool bMatch = true;
int index = 0;
string ret = "";

while (bMatch)
{
foreach (var item in strs)
{
if (index >= item.Length || item[index] != strs[0][index])
{
bMatch = false;
return ret;
}
}

ret += strs[0][index];
index++;
}

return ret;
}


代码分析:

  简单BF。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: