前端算法面试题-1

87 阅读1分钟

1.统计字符出现次数

// 写法1
function calcCharCount(str) {
    let res = {};

    for (let i = 0; i < str.length; i++) {
        const key = str[i];
        if (res[key]) {
            res[key] += 1;
        } else {
            res[key] = 1;
        }
    }

    return res;
}

// 写法2
function calcCharCount(str) {
    return [...str].reduce((res, key) => {
        if (res[key]) {
            res[key] += 1;
        } else {
            res[key] = 1;
        }
        return res;
    }, {});
}

// 简写
function calcCharCount(str) {
    return [...str].reduce((res, key) => (res[key]++ || (res[key] = 1), res), {});
}

const res = calcCharCount("hello world!");
console.log("res", res); // { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1, '!': 1 }

2. 单词首字母大写

function capitalize(str) {
    let arr = str.split(" ");
    return arr.map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(" ");
}

const res = capitalize("coder");
console.log(res); // Coder

3. 无重复字符的最长子串 [数组-3]

/**
 * @param {string} str
 * @return {number}
 */
function lengthOfLongestSubstring(str) {
    let l = 0; // 定义左指针
    let res = 0; // 结果
    let map = new Map(); // 存放字符和对应下标
    for (let r = 0; r < str.length; r++) {
        // 如果出现重复字符,则把左指针移到重复字符的下一位(注意同时满足重复字符的索引大于左指针)
        if (map.has(str[r]) && map.get(str[r]) >= l) {
            l = map.get(str[r]) + 1;
        }

        res = Math.max(res, r - l + 1);
        map.set(str[r], r); // 设置字符和下标 {a => 0, b => 1, c => 2}
        
    }

    return res;
}

const res = lengthOfLongestSubstring("abcabc");
console.log(res); // 3

4. 数组交集 [数组-350]

/** 原理:
 * 1. 属于查找表的算法,如跟次数有关,使用map
 * 2. 定义res存放两数组交集的结果
 * 3. 定义map,用于存放数组中出现的字符和次数
 * 4. 开始遍历nums1,如果map中有当前遍历的值,则次数+1;如果map中没有当前遍历的值,则表示当前的值只有一个,设置次数为1
 * 5. 开始遍历nums1,如果map中有当前遍历的值,则表示当前值是两个数组的交集,把当前值push到res中;同时将map中出现当前值的次数-1
 * 6. res存储的是两个数组的交集,返回即可
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
function intersection(nums1, nums2) {
    const res = [];
    const map = new Map();

    for (let i = 0; i < nums1.length; i++) {
        if (map.has(nums1[i])) {
            map.set(nums1[i], map.get(nums1[i]) + 1);
        } else {
            map.set(nums1[i], 1);
        }
    }

    for (let i = 0; i < nums2.length; i++) {
        if (map.get(nums2[i])) {
            res.push(nums2[i]);
            map.set(nums2[i], map.get(nums2[i]) - 1);
        }
    }

    return res;
}

const res = intersection([1, 2, 3, 3, 5, 7], [2, 3, 3, 4, 7]);
console.log(res); // [2, 3, 3, 7]