Skip to content

Latest commit

 

History

History
40 lines (29 loc) · 1.18 KB

1002-查找常用字符.md

File metadata and controls

40 lines (29 loc) · 1.18 KB

1002-查找常用字符

原题

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

示例 1:

输入:["bella", "label",  "roller"]
输出:["e", "l", "l"]

示例 2:

输入:["cool", "lock", "cook"]
输出:["c", "o"]

解法

const commonChars = function (A) {
    let res = A[0].split('');
    for (let i = 1; i < A.length; i++) {
        let tmp = A[i].split('');
        res = res.filter(v => {
            let index = tmp.indexOf(v);
            // 这一步最关键,为什么要 tmp[index] = 1 呢,因为要把已经判断过的,下一次不要再进行判断
            // 因为题目是每一个数组是字符串,这里设置成数字,就相当于设置当前判断完下次tmp.indexOf(v)就不会再判断当前已经判断过的值了
            return index !== -1 ? tmp[index] = 1 : false;
        });
    }
    return res;
}