面試題 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;
    }
};

這數據彷彿不太科學code

執行用時 :8 ms, 在全部 C++ 提交中擊敗了97.61%的用戶
內存消耗 :8.7 MB, 在全部 C++ 提交中擊敗了100.00%的用戶
相關文章
相關標籤/搜索