Java实现-最长公共前缀
程序员文章站
2024-02-24 22:38:16
...
public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
if(strs.length==0){
return "";
}
int min=Integer.MAX_VALUE;
String minStr="";
for(int i=0;i<strs.length;i++){
if(min>strs[i].length()){
minStr=strs[i];
min=strs[i].length();
}
}
if(min==0){
return "";
}
for(int i=min;i>=0;i--){
String standard=minStr.substring(0, i);
int j=0;
for(j=0;j<strs.length;j++){
if(strs[j].substring(0, i).equals(standard)){
continue;
}else{
break;
}
}
if(j==strs.length){
return standard;
}
}
return "";
}
}