题意:找到字符串数组中最长的公共全缀
思路:思路将最短的字符串当做哨兵,记录与当前字符串相同的前缀的位置index,直到和数组中的全部字符串比较完成
public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0){ return new String(); //guard clause } int minLen = strs[0].length(); int eleIndex = 0; for(int i = 1; i < strs.length; i++){ if(strs[i].length() < minLen){ eleIndex = i; minLen = strs[i].length(); } } String str = strs[eleIndex]; int index = minLen; for(int i = 0; i < strs.length; i++){ for(int j = 0; j < index; j++){ //和第i个字符串比较前缀 if(str.charAt(j) != strs[i].charAt(j)){ index = j; break; } } } return str.substring(0, index); }