let longestCommonPrefix = function(strs) { let re = ''; if (!strs.length) return re; for (let j=0;j<strs[0].length;j++){//第j位 for (let i=1;i<strs.length;i++){//第i个 if (strs[i][j]!=strs[0][j]) return re } re += strs[0][j]; } return re; };
解一的递归版本,需要增加一些判断语句。
1 2 3 4 5 6 7 8 9 10 11 12
let longestCommonPrefix = function (strs,re = '') { if (!strs.length) return re; if (strs.length == 1) return strs[0]; for (let i = 1; i < strs.length; i++) { if (!strs[i][0]) return re if (strs[i][0] != strs[0][0]) return re strs[i] = strs[i].slice(1,strs[i].length); } re += strs[0][0]; strs[0] = strs[0].slice(1,strs[0].length); return longestCommonPrefix(strs, re); };