码迷,mamicode.com
首页 > Web开发 > 详细

LeetCode "Encode and Decode Strings"

时间:2015-08-29 06:10:34      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:

This is about https://en.wikipedia.org/wiki/Run-length_encoding. The trick is, for a valid char, we only compress up to 254 occurences - count 255 means end of a string.

typedef unsigned char UCHAR;
class Codec {
    const static int MAX_CNT = 255;
public:

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string ret;
        for(auto &s : strs)
        {
            int i = 0, len = s.length();
            
            while(i < len)
            {
                UCHAR c = s[i];
                UCHAR cnt = 1;
                while(i < len - 1 && s[i + 1] == c && cnt < (MAX_CNT - 1))
                {
                    i ++; cnt ++;
                }
                ret += UCHAR(cnt);
                ret += UCHAR(c);
                
                i ++;
            }
            ret += UCHAR(MAX_CNT); // 0xFF: end
        }
        return ret;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) 
    {
        vector<string> ret;

        size_t len = s.length();
        string cur; int inx = 0;
        while(inx < len)
        {
            UCHAR cnt = s[inx];
            if(cnt == UCHAR(MAX_CNT))
            {
                ret.push_back(cur);
                cur = "";
                inx ++;
                continue;
            }
            //
            UCHAR c = s[inx + 1];
            for(UCHAR i = 0; i < cnt; i ++)    cur += c;
            inx += 2;                        
        }
        return ret;
    }
};

LeetCode "Encode and Decode Strings"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4768262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!