美文网首页
271. Encode and Decode Strings

271. Encode and Decode Strings

作者: 丁不想被任何狗咬 | 来源:发表于2016-08-10 14:28 被阅读52次
  1. Encode and Decode Strings

编码解码字符串

这道题只需要用\转义,用/分割就可以了,可能需要注意判断decode的时候如果为"/"则为{""}
注意:不能用/转义,用/分割。这样的话无法无脑解决["",""]这种情况,或者说///就没办法确定是什么了。

class Codec {
public:

    // Encodes a list of strings to a single string.
    // use '/' to end strings, use '\' to escape
    string encode(vector<string>& strs) {
        string encode_string;
        for(auto str : strs) {
            for(auto c: str) {
                if(c == '/' || c == '\\') {
                    encode_string += '\\';
                }
                encode_string += c;
            }
            encode_string += '/';
        }
        return encode_string;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        if(s == "/") {
            return {""};
        }
        vector<string> decode_string;
        string cur_str;
        for(int i = 0; i < s.size();) {
            if(s[i] == '\\') {
                cur_str += s[i+1];
                i += 2;
            } else if(s[i] == '/') {
                decode_string.push_back(cur_str);
                cur_str = "";
                i++;
            } else {
                cur_str += s[i];
                i ++;
            }
        }
        return decode_string;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));    

相关文章

网友评论

      本文标题:271. Encode and Decode Strings

      本文链接:https://www.haomeiwen.com/subject/nohjsttx.html