【LeetCode】 面试题 01.06. Compress String LCCI 字符串压缩(Easy)(JAVA)

【LeetCode】 面试题 01.06. Compress String LCCI 字符串压缩(Easy)(JAVA)

题目地址: https://leetcode.com/problems/rotate-list/

题目描述:

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the “compressed” string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (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

题目大意

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

解题方法

非常简单的一题,直接判断连续相同字符个数就行

class Solution {
    public String compressString(String S) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < S.length(); i++) {
            int count = 1;
            char ch = S.charAt(i);
            i++;
            while (i < S.length() && ch == S.charAt(i)) {
                i++;
                count++;
            }
            res.append(ch).append(count + "");
            i--;
        }
        if (res.length() < S.length()) {
            return res.toString();
        }
        return S;
    }
}

执行用时 : 10 ms, 在所有 Java 提交中击败了 41.93% 的用户
内存消耗 : 42.1 MB, 在所有 Java 提交中击败了 100.00% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2276

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104891677