查找字符串数组中的最长公共前缀
![](https://img2022.cnblogs.com/blog/608798/202211/608798-20221110214823008-2119297096.png)
import java.util.*;
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
//找出数组中最小的字符串,遍历字符串的子串,从最大至最小
//判断是否满足公共前缀,若全部满足则返回这个子串
if(strs.length == 0){
return "";
}
String minStr = strs[0];
for(int i=1; i<strs.length; i++){
if(strs[i].length()<minStr.length()){
minStr = strs[i];
}
}
String subString = "";
boolean flag = false;
for(int j=0; j<=minStr.length(); j++){
subString = minStr.substring(0,minStr.length()-j);
for(int k=0; k<strs.length; k++){
if(strs[k].indexOf(subString)==-1){
break;
}
if(k==strs.length-1){
flag = true;
}
}
if(flag==true){
return subString;
}
}
return "";
}
}