Skip to content

Instantly share code, notes, and snippets.

@xydiva
Last active May 10, 2018 02:38
Show Gist options
  • Save xydiva/7c93be79decf0a76f1a54467230a896c to your computer and use it in GitHub Desktop.
Save xydiva/7c93be79decf0a76f1a54467230a896c to your computer and use it in GitHub Desktop.
利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能(比如:字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”)
function countString(str) {
    const arr = str.split('');
    let n = 1;
    let result = '';
    for (let i = 0; i < arr.length; i++) {
        if (arr[i + 1] === arr[i]) {
            n++;
        }
        else {
            result += arr[i] + n;
            n = 1;
        }
    }
    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment