为什么做网站备案的人态度差/近三天时政热点
题目
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,则返回""
示例:
输入: ["flower","flow","flight"] 输出: "fl"
分析
将第一个元素设为基准,从第二个元素开始,依次判断是否前缀为基准,进行判断。
public static String solution(String[] strs) {if (strs.length == 1){return strs[0];}String base = strs[0];int common = 0;boolean stop = false;for (int i = 1; i <= base.length(); i++){String temp = base.substring(0, i);for (int j = 1; j < strs.length; j++){if (strs[j].indexOf(temp) != 0){stop = true;break;}}if (stop){break;}common = i;}if (common == 0){return "";} else {return base.substring(0, common);}}