面试题 01.06. Compress String LCCI(Leetcode每日一题-2020.03.16)

Problem

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).

Note:

0 <= S.length <= 50000

Example1

Input: “aabcccccaaa”
Output: “a2b1c5a3”

Example2

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

Solution

别忘了最后一个字母的处理

class Solution {
public:
    string compressString(string S) {
        if(S.length() <=2)
            return S;

        string compressedS;

        char curChar = S[0];
        int curCharCnt = 0;
        for(int i = 0;i<S.length();++i)
        {
            if(S[i] == curChar)
            {
                ++curCharCnt;
            }
            else
            {
                compressedS += curChar;
                compressedS += to_string(curCharCnt);

                curChar = S[i];
                curCharCnt = 1;
            }

        }

        //Do not forget to process last character
        compressedS += curChar;
        compressedS += to_string(curCharCnt);


        if(compressedS.length() < S.length())
            return compressedS;
        else
            return S;

    }
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104906151