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

《程序员面试金典(第 6 版)》 01.06. 字符串压缩 #75

Open
Tcdian opened this issue Mar 19, 2020 · 1 comment
Open

《程序员面试金典(第 6 版)》 01.06. 字符串压缩 #75

Tcdian opened this issue Mar 19, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 19, 2020

《程序员面试金典(第 6 版)》 01.06. 字符串压缩

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

Example 1

Input: "aabcccccaaa"
Output: "a2b1c5a3"

Example 2

Input: "abbccd"
Output: "abbccd"
Explanation: 
The compressed string is "a1b2c2d1", which is longer than the original string.

Note

  • 0 <= S.length <= 50000
@Tcdian Tcdian changed the title 面试题 01.06. 字符串压缩 程序员面试金典 01.06. 字符串压缩 Mar 19, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 19, 2020

Solution

  • JavaScript Solution
/**
 * @param {string} S
 * @return {string}
 */
var compressString = function(S) {
    if (S.length <= 2) {
        return S;
    }
   let base = 0;
   let result = '';
   for (let i = 1; i <= S.length; i++) {
       if (i === S.length || S[base] !== S[i]) {
           result += S[base] + (i - base);
           base = i;
       }
   }
   return S.length > result.length ? result : S;
};

@Tcdian Tcdian changed the title 程序员面试金典 01.06. 字符串压缩 《程序员面试金典(第 6 版)》 01.06. 字符串压缩 Mar 24, 2020
@Tcdian Tcdian added the String label May 3, 2020
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