【发布时间】:2020-12-12 10:52:52
【问题描述】:
我正在尝试使用 java 在字符串数组中查找最长的公共前缀。以下是我的解决方案,但是当我在 leetcode 上上传它时,它失败了,我不明白哪个测试用例失败了。我测试过的所有测试用例都运行良好。
我的方法是匹配字符串数组中所有单词的第一个字符,如果所有单词的第一个字符相似,则移动到第二个字符,否则函数返回字符串。
如果有人帮助我确定我的代码失败的测试用例,我将非常感激。以下是我写的代码:
public static String LongCommonPrefix(String[] strs)
{
String commonPrefix="";
int count=0, k=0;
if(strs.length>0)
{
for(int i=0; i<strs[0].length(); i++)
{
int j=1;
while(j<strs.length)
{
if(strs[0].charAt(k)==strs[j].charAt(k))
{
count++;
j++;
}
else
break;
}
if(count==strs.length-1)
{
commonPrefix+=strs[0].charAt(k);
count=0;
k++;
}
else
{
return commonPrefix;
}
}
}
return commonPrefix;
}
【问题讨论】:
标签: java arrays string character prefix