百词斩线上笔试

发布时间 2023-05-04 11:01:28作者: 南韵

s为非空英文字符串,要将通类型的压缩为字符串s2,且s1长度不得超过100

如:s为 aaabcccc,s2应为a3bc4

function f(s) {
    if (!s || (s.length > 100)) {
        return ;
    } else {
        const tempArr = [];
        let keyArr = Array.from(new Set(s));
        const tempS = s.split('');
        keyArr.map(key => {
            let count = 0;
            tempS.forEach(item => {
                if (item === key) {
                    count++;
                }
            })
            if(count === 1) {
              tempArr.push(key)
            } else {
                tempArr.push(key+count);
            }
        })
        
        return tempArr.join('');
    }
}

f('abbccdeeeee')