编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
设第一个字符为前缀,然后不断剪短让其成为以后字母的前缀,剩下的前缀即为所有字符的前缀
用strs[i].indexOf(pre)为不为0(为0则为前缀)检查是否为。
class Solution {
public String longestCommonPrefix(String[] strs) {
//空的情况
if(strs==null||strs.length==0){
return "";
}
int l=strs.length;
String pre=strs[0];
int i=1;
//遍历所有字符
while(i<l){
while(strs[i].indexOf(pre)!=0){
// 不断剪短使成为前缀
pre=pre.substring(0,pre.length()-1);
}
i++;
}
return pre;
}
}