Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符串压缩 #27

Open
CodeRookie262 opened this issue Jan 21, 2021 · 1 comment
Open

字符串压缩 #27

CodeRookie262 opened this issue Jan 21, 2021 · 1 comment
Labels

Comments

@CodeRookie262
Copy link
Owner

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

示例1:

 输入:"aabcccccaaa"
 输出:"a2b1c5a3"

示例2:

 输入:"abbccd"
 输出:"abbccd"

解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。

来源:LeetCode - 字符串压缩

@CodeRookie262
Copy link
Owner Author

var compressString = function(S) {
    let ans = '',
        s = S[0],
        sort = 1;
        for(var i = 1,l = S.length;i < l;i++){
            if(s === S[i]) {
                sort++
            }else{
                ans = ans + s + sort;
                s = S[i];
                sort = 1 
            }
        }
        ans = ans + s + sort;
        return S.length <= ans.length ? S : ans
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant