Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question.
这个题目的中文意思很简单:
给出一个String数组,求出数组中最长的公共前缀,即所有数组元素开头的最长字符串。
相信一般人看到这个题都会知道解题思路,很简单,这里只说明一点,如果这个最长前缀存在的话,那么它一定也存在于长度最小的字符串中,且遍历这个最小的字符串的时候,最好是从最长也就是整个字符串开始,然后右侧指针左移。
java代码如下:
if(strs.length==0) return "";
if(strs.length==1) return strs[0];
String str_temp = strs[0];
for(int i=0;i<strs.length;i++)
{
if(strs[i].length()<str_temp.length()){
str_temp = strs[i];
}
}
String ans = "";
for(int i=0;i<str_temp.length();i++){
String flag = str_temp.substring(0, str_temp.length()-i);
int count = 0;
for(int j=0;j<strs.length;j++){
if(strs[j].startsWith(flag)){
count++;
}
}
if(count==strs.length){
ans = flag ;
return flag;
}
}
return ans;
代码中设置了一个计数字段,如果以temp开头,则计数加一,循环后,如果结果为数组长度,即所有元素都以此开头,则为最长返回。