程序员面试金典 面试题 01.06. 字符串压缩

问题描述

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

示例1:

 输入:"aabcccccaaa"
 输出:"a2b1c5a3"
示例2:

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

字符串长度在[0, 50000]范围内。

代码1

class Solution {
public:
    string compressString(string S) {
        char t = S[0];
        int count = 0;
        string ans;
        ans += t;
        for(auto s:S)
        {
            if(s == t)
                ++count;
            else{
                ans += to_string(count);
                count = 1;
                t = s;
                ans += t;
            }
        }
        ans += to_string(count);
        return ans.size()>=S.size()?S:ans;
    }
};

结果

执行用时 :16 ms, 在所有 C++ 提交中击败了43.83%的用户
内存消耗 :7.3 MB, 在所有 C++ 提交中击败了100.00%的用户

代码2

class Solution {
public:
    string compressString(string S) {
        if(S.size() < 1)return S;
        stringstream str;
        str << S[0];
        int count = 1;
        char t = S[0];
        for(int i = 1; i < S.size(); ++i)
        {
            if(S[i] == t)++count;
            else{
                str << count << S[i];
                count = 1;
                t = S[i];
            }
        }
        str << count;
        string ans = str.str();
        return ans.size()<S.size()?ans:S;
    }
};

结果

执行用时 :4 ms, 在所有 C++ 提交中击败了99.75%的用户
内存消耗 :7.6 MB, 在所有 C++ 提交中击败了100.00%的用户

代码3

class Solution {
public:
    string compressString(string S) {
        if(S.size() < 1)return S;
        ostringstream str;
        int count = 1;
        char t = S[0];
        for(int i = 1; i < S.size(); ++i)
        {
            if(S[i] == t)++count;
            else{
                str << t << count;
                count = 1;
                t = S[i];
            }
        }
        str << t << count;
        string ans = str.str();
        return ans.size()<S.size()?ans:S;
    }
};

结果

执行用时 :4 ms, 在所有 C++ 提交中击败了99.75%的用户
内存消耗 :7.8 MB, 在所有 C++ 提交中击败了100.00%的用户
posted @ 2020-05-31 09:01  曲径通霄  阅读(148)  评论(0编辑  收藏  举报