最长公共前缀

获取到数组内的所有值的公共部分

题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例:

输入: ["flower","flow","flight"]
输出: "fl"

思路

反转方式:

  • 方案一:将第一个字符串设为公共字符串转换为数组,将所有字符串进行循环转换成数组,然后按顺序进行比较,如果不相等,则在公共字符串中剔除当前及之后的字符串。

  • 方案二:将第一个字符串设为公共字符串,使用 indexOf 判断后面的每一项是否存在于公共字符串内,若没有则剔除最后一个字符串,以此类推。

解题

方案一:转换成数组进行比较

var longestCommonPrefix = function(strs) {
    if (strs.length <= 0) return "";
    let common = strs[0].split("");
    strs.map(item => {
        const current = item.split("");
        const currentLen = current.length;
        // 如果当前项的位数小于公共部分,则裁剪公共部分
        if (currentLen < common.length) {
            common = common.slice(0, currentLen);
        }
        for (let i = 0; i < currentLen; i++) {
            if (current[i] !== common[i]) {
                common = common.slice(0, i);
                break;
            }
        }
    });
    return common.join(",").replace(/,/g, "");
};

方案二:使用 indexOf 进行比较

var longestCommonPrefix = function(strs) {
    if (strs.length <= 0) return "";
    let common = strs[0];
    for (let i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(common) !== 0) {
            common = common.substring(0, common.length - 1);
        }
    }
    return common;
};
作者

BiteByte

发布于

2020-08-08

更新于

2024-01-11

许可协议