xiqe / code-train

前端算法

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

查找常用字符

xiqe opened this issue · comments

查找常用字符

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

你可以按任意顺序返回答案。

示例 1:

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

示例 2:

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

提示:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] 是小写字母

reply

var commonChars = function(A) {
    // 如果A小于2的长度,返回[]
    if(A.length<2) return [];
    let result = [];
    // 将A[0]作为参照字符串进行遍历
    for(let i=0;i<A[0].length;i++){
        // 设置计数器
        let count = 0;
        // 将A[0][i]与A数组中除了A[0]本身的字符串遍历
        for(let j=1;j<A.length;j++){
            let _i = A[j].indexOf(A[0][i]);
            // 如果A[j]包含A[0][i],则count+1;并且去除A[j]中的该字母,作为去重
            if(_i>-1){
                A[j] = A[j].substring(0,_i) + A[j].substring(_i+1);
                count++;
            }
        }
        // 如果计数器等于数组长度-1,则说明该元素是符合条件的
        if(count == A.length - 1){
            result.push(A[0][i])
        }
    }
    return result
};