/**
*编写一个函数来查找字符串数组中的最长公共前缀。
* 如果不存在公共前缀,返回空字符串 ""。
* 说明: 所有输入只包含小写字母 a-z 。
*/
/** *编写一个函数来查找字符串数组中的最长公共前缀。 * 如果不存在公共前缀,返回空字符串 ""。 * 说明: 所有输入只包含小写字母 a-z 。 */ public class Main53 { public static void main(String[] args) { String[] strs = {}; System.out.println(Main53.longestCommonPrefix(strs)); } public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length < 1) { return ""; } String result = strs[0]; for(int i=1; i<strs.length; i++){ if(!strs[i].startsWith(result)){ result = result.substring(0, result.length()-1); i--; // 新的字符串以 整个result 开头的话继续循环下去 // 新的字符串不以 整个result 开头的话就将result这个字符串最后一位砍掉,并再次比较。 } } return result; } }