【JS】简单字符串算法题 压缩、去重

let str = "aaaaabbbcccccaabcccc";
    // 压缩字符串
    const zipStr = (str) => {
        let arr = str.split('');
        let resultStr = '';
        let strLength = 1;
        for(let i =0; i < arr.length; i++) {
            if(arr[i] === arr[i+1]) {
                strLength++;
            } else {
                resultStr += arr[i] + strLength;
                strLength = 1;
            }
        }
        return resultStr;
    }
    // 去除重复字符
    const shortStr = (str) => {
        let arr = str.split('');
        let resultArr = [];
        for(let i =0; i < arr.length; i++) {
            if(arr[i] !== arr[i+1]) {
                resultArr.push(arr[i]);
            }
        }
        const resultStr = Array.from(new Set(resultArr)).join(''); 
        return resultStr;
    }

    // console.log(zipStr(str));
    console.log(shortStr(str));

 

posted on 2026-04-04 21:04  贲风  阅读(12)  评论(0)    收藏  举报