Open github-actions[bot] opened 2 years ago
// @lc code=start
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 1) return strs[0];
const arr = strs.sort((a, b) => a.length - b.length);
let res = arr[0];
let i = res.length - 1;
while (i >= 0) {
for (j = 1; j < arr.length; j++) {
if (!arr[j].startsWith(res)) {
res = res.slice(0, i);
i--;
break;
}
if (j === arr.length - 1) {
i = -1;
}
}
}
return res;
};
// @lc code=end
14 Longest Common Prefix