C++ solution simple idea,


  • 0
    L
    string encode(vector<string>& strs) {
      if (strs.empty()) return "";
      ostringstream ostr;
      const int size_in = strs.size();
      ostr << size_in << "#";
      for (int i = 0; i < size_in; i++) {
          ostr << strs[i].size() << "$";
      }
      for (auto &word : strs) ostr << word;
      return ostr.str();
    }
    
    // Decodes a single string to a list of strings.
    vector<string> decode(string str) {
      if (str == "") return vector<string>();
      istringstream istr(str);
      int total_num;
      istr >> total_num;
      istr.seekg(1, ios::cur);
      vector<int> lens;
      vector<string> res;
      for (int i = 0; i < total_num; i++) {
          int word_len = 0;
          istr >> word_len;
          istr.seekg(1, ios::cur);
          lens.push_back(word_len);
      }
      assert(total_num == lens.size());
      for (int i = 0; i < total_num; i++) {
         char *buf = new char[lens[i]+1];
         istr.read(buf, lens[i]);
         buf[lens[i]] = '\0';
         cout <<"len[i]->" << lens[i] << " buf->" << buf << endl;
         res.push_back(string(buf));
      }
     return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.