求数组中各元素的最长的公共前缀
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
解法
var longestCommonPrefix = function(strs) {
if (strs.length === 0) return '';
return strs.reduce((result, s) => {
return longestInTwo(result, s);
});
};
const longestInTwo = (a, b) => {
let long, short;
if (a.length > b.length) {
long = a;
short = b;
} else {
long = b;
short = a;
}
while (long.indexOf(short) !== 0) {
short = short.slice(0, -1);
}
return short;
};
网友评论