public class Program {
public string Longest(string[] strs) {
int m = strs[0].Length;
int n =0;
//找出最短的字符串并返回下标
for(int i=1;i<strs.Length;i++)
{
if(m>strs[i].Length)
{
m=strs[i].Length;
n=i;
}
}
string num = "";//用于储存公共字符
//用最短字符串的所有字符与其他字符比较
for(int j=0;j<strs[n].Length;j++)
{
int count = 0;//用于判断是否所有字符的第j+1个字符相等
for(int k=0;k<strs.Length;k++)
{
if(strs[n][j]!=strs[k][j])
{
break;
}
else
{
count++;
if(count==strs.Length)
num += strs[k][j];
}
}
}
return num;
}
}
编写一个函数求出字符串数组中所有字符串的最大前缀
本文介绍了一种寻找字符串数组中最长公共前缀的算法实现。通过先确定数组中最短的字符串,然后逐个字符地与其他字符串进行比较,来找出所有字符串共有的前缀部分。

被折叠的 条评论
为什么被折叠?



