编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
public class Solution {
public string LongestCommonPrefix(string[] strs) {
string publicString = "";
bool isPublic=false;
for (int i = 0; i < strs[0].Length; i++)
{
for (int j = 0; j < strs.Length - 1; j++)
{
if (i >= strs[j+1].Length)
{
isPublic = false;
break;
}
if (strs[j][i] == strs[j + 1][i])
{
isPublic = true;
continue;
}
else
{
isPublic = false;
break;
}
}
if (isPublic == true)
{
publicString += strs[0][i];
}
else
{
break;
}
}
if (strs.Length == 1)
{
publicString = strs[0];
}
return publicString;
}
}