#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Codec { public: string encode(vector<string>& strs) { string ret = ""; for (int i = 0; i < strs.size(); i++) { ret += to_string(strs[i].size()) + "#" + strs[i]; } return ret; } int getNext(char x, int start, string s){ int idx = s.size(); for (int i = start; i < s.size(); i++) { if (s[i] == x) { idx = i; break; } } return idx; } vector<string> decode(string s) { vector<string> ret; int i = 0; int n = s.size(); while (i < n) { int hashPos = getNext('#', i, s); int len = stoi(s.substr(i, hashPos - i)); i = hashPos + 1; ret.push_back(s.substr(i, len)); i += len; } return ret; } }; main(){ Codec ob; vector<string> v = {"hello", "world", "coding", "challenge"}; string enc = (ob.encode(v)); cout << "Encoded String " << enc << endl; print_vector(ob.decode(enc)); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter