编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
方法一:
class Solution
{
public String longestCommonPrefix(String[] strs)
{
if (strs.length==0) //判断字符串是否为空
return "";
if (strs.length==1) //若只有一1个,则其为公共前缀
return strs[0];
int preLength = strs[0].length();
int strsNum = strs.length;
String pre = strs[0];
for (int i=1 ;i<strsNum;i++) //找到其中最短的一个字符串
{
if(preLength >strs[i].length())
{
preLength = strs[i].length();
pre = strs[i];
}
}
while (preLength>0)
{
int flag = 0; //标记是否为公共前缀
for(int i=0;i<strs.length;i++)
{
if(pre.equals(strs[i].substring(0,preLength))==false)
{
System.out.println("不是最长公共前缀");
pre = newPre(pre,preLength);
preLength--;
flag = 1;
break;
}
}
if (flag == 0 )
{
return pre;
}
}
return pre;
}
public String newPre(String oldPre,int oldLength)
{
int newLength = oldLength-1;
if (newLength == 0)
{
return "";
}
String nPre = oldPre.substring(0,newLength);
// System.out.println("新字符串:"+nPre);
return nPre;
}
}
方法二 :
class Solution
{
public String longestCommonPrefix(String[] strs)
{
if(strs.length==0)
return "";
String s=strs[0];
for (String string : strs)
{
while(!string.startsWith(s))
{
if(s.length()==0)
return "";
s=s.substring(0,s.length()-1);
}
}
return s;
}
}