面试题 01.06. 字符串压缩

面试题 01.06. 字符串压缩

不原地改了
还是另开一个string舒服;

class Solution {
public:
    string compressString(string S) {
        int n = S.length();
        if(n<2) return S;
        string res;
        char c = S[0];
        int cnt = 1;
        res += S[0];
        for(int i = 1; i<n; ++i) {
            if(S[i]==c) {
                ++cnt;
                continue;
            }else {
                res += to_string(cnt);
                c = S[i];
                cnt = 1;
                res += S[i];
            }
        }
        res += to_string(cnt);
        return (res.length() < n)? res: S;
    }
};

这数据仿佛不太科学

执行用时 :8 ms, 在所有 C++ 提交中击败了97.61%的用户
内存消耗 :8.7 MB, 在所有 C++ 提交中击败了100.00%的用户
原文地址:https://www.cnblogs.com/owxc/p/12507088.html