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 ""; } }
标签:return,前缀,strs,查找,数组,字符串,String From: https://www.cnblogs.com/northli/p/16878924.html