Skip to content

字符串压缩 #27

Open
Open

Description

@CodeRookie262

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

示例1:

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

示例2:

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

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

来源:LeetCode - 字符串压缩

Activity

  1. CodeRookie262 commented on Jan 22, 2021

    @CodeRookie262
    OwnerAuthor
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions