pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

最长公共前缀 #1048

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

14. 最长公共前缀

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    if(!strs.length)
        return "";
    const len = strs.length,
        chars = [];
    for(let i=0, strLen=strs[0].length; i<strLen; i++) {
        for(let j=1; j<len; j++) {
            if(strs[j][i] != strs[0][i]) {
                return chars.join("");
            }
        }
        chars.push(strs[0][i]);
    }
    return chars.join("");
};