LeetCode 271. 字符串的编码与解码

基本思想:

很有建设性的一道题;

涉及以下知识点:

  1. TCP和UDP字符计数;
  2. sprintf的进制转换问题,可以将int等类型转换为各种进制,并且用char数组接受;
  3. 非十进制转string问题,可以用stoi,自己之前全用的atoi;

基本代码:

class Codec {
public:
    string int2string(int num){
        char ch[16];
        sprintf(ch, "%x",num);
        string ret(ch);
        while(ret.size()<4)
            ret='0'+ret;
        return ret;
    }

    int string2int(string s){
        int ret=stoi(s,0,16);
        return ret;
    }

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string ret="";
        for(auto str:strs){
            ret+=int2string(str.size());
            ret+=str;
        }
        return ret;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string>ret;
        int index=0;
        while(index<s.size()){
            int lenght=string2int(s.substr(index,4));
            index+=4;
            ret.push_back(s.substr(index,lenght));
            index+=lenght;
        }
        return ret;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值